关于 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
5年前 评论
joeyun (楼主) 5年前
Jason990420 (作者) 5年前
讨论数量: 7

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

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

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

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

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

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

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

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

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

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

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

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

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