比较不同excel工作簿中的2列:Python

时间:2016-11-21 11:18:39

标签: python excel openpyxl

我试图在Python中使用Ppenpyxl比较不同工作簿中的2个Excel列。到目前为止,我得到的是:

#Load the workbooks
wkb1 = load_workbook(filename = os.path.join(srcdir, "wbk1.xlsx"))
wkb2 = load_workbook(filename = os.path.join(srcdir, "wbk2.xlsx"))
#Find the last row of the excel data
ws1 = wkb1.active
wkb1_LastRow = ws1.max_row
ws2 = wkb2.active
wkb2_LastRow = ws2.max_row

for xrow in range (1,(wkb1_LastRow+1)):  
    for yrow in range (1,(wkb2_LastRow+1)):
        print (ws1.cell(row=xrow, column=1).value, ws2.cell(row=yrow, column=1).value )
        if ws1.cell(row=xrow, column=1).value == ws2.cell(row=yrow, column=1).value:
            print('HIT')  

即使2列包含相同的值,if语句也总是失败:

...
3145728 3145728,
3145728 3145729,
3145728 3145730,
3145728 3145731,
...

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

使用嵌套循环的FWIW不是这样做的方法。使用zip要简单得多。

以下内容应该有效:

for src, target in zip(ws1['A'], ws2['A']):
   if src.value == target.value:
       print("Hit")