openpyxl检查行是否包含两个单独值的单元格

时间:2019-11-12 17:18:47

标签: python python-3.x openpyxl

我可以遍历行中的单元格以检查包含特定值的单元格。现在,我正在尝试检查该行是否还包含第二个值。

target = input("Input cell value: ")
target2 = input("Input second cell value ")
wb = openpyxl.load_workbook("file.xlsx")
ws = wb.active
for ws in wb.worksheets:
    for row in ws.iter_rows():
        for cell in row:
            if cell.value == target: 
            # I'd also like to check if row contains second target
                print(cell.value)

1 个答案:

答案 0 :(得分:1)

我仍然不确定我是否真的了解这个问题,但是解决此问题的最佳方法是使用集合一次比较所有值。

targets = {target, target2}
for idx, row in enumerate(ws.iter_rows(values_only=True),1):
    if set(row) & targets:
        print(f"Row {idx} contains all the values")
相关问题