关于 openpyxl 中比对某一列中是否存在某个值的问题

为了实现搜索这一列中是否存在要插入数据的某个值,于是比对这个值在这一列中是否存在,返回bool

wb = load_workbook(os.path.dirname(__file__) + "\data.xlsx")
sheet = wb.worksheets[0]
# 遍历某一列中是否存在某个值
def is_exist(value):
    col = sheet['b']
    for cell in col:
        return value == str(cell.value)

if __name__ == "__main__":
    print(is_exist('301'))

这一列明明有这个数据,而且没有空格之类,为什么一直返回的是false

Jason990420
最佳答案

下面这段执行比较快, 但比较占内存

def is_exist(value):
    col = sheet['B']
    col_str = list(map(str, [c.value for c in col]))
    return value in col_str
4年前 评论
joeyun (楼主) 4年前
Jason990420 (作者) 4年前
讨论数量: 7

确认单元格没有不可见字符,打印出 cell.value实际看看。代码是查的b列,301上面的bh是啥?是列吗 ?老铁

4年前 评论
joeyun (楼主) 4年前
laodong114 (作者) 4年前
Jason990420

你确定你清楚这是作什么?
比较所有的cell, 还是只比较第一个cell ('表头') ?

for cell in col:
    return value == str(cell.value)
4年前 评论
joeyun (楼主) 4年前
Jason990420

你的代码就是只有在比较表头........

4年前 评论
joeyun (楼主) 4年前
Jason990420

晕….你那个也只比对表头, 下面这段执行比较慢, 但比较不占内存

def is_exist(value):
    col = sheet['B']
    for cell in col:
        if value == str(cell.value):
            return True
    return False
4年前 评论
joeyun (楼主) 4年前
Jason990420

下面这段执行比较快, 但比较占内存

def is_exist(value):
    col = sheet['B']
    col_str = list(map(str, [c.value for c in col]))
    return value in col_str
4年前 评论
joeyun (楼主) 4年前
Jason990420 (作者) 4年前
Jason990420

是B列啊
col = sheet['B']

4年前 评论
joeyun (楼主) 4年前
Jason990420
for i, cell in enumerate(col):
    # if True: return i 

# if value in col_str: return col_str.index(value)
4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!