要使用openpyxl将excel中的两列与唯一列进行比较吗

2024-09-29 06:23:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,在过去的几周里一直在学习。 我想使用openpyxl比较excel中的两列和唯一列

Excel1:

Area_Code    Representative Name
1                 Jim
2                 Pam
3                 Mike
4                 Ryan
5                 Kelly
6                 Andy
7                 Robert
11                Roy

Excel2:

Area_Code    Representative_Name
1                 Jim
2                 Pam
3                 Mike
4                 Ryan
5                 Kelly
6                 Andy
7                 Roberto
8                 Oscar
9                 Angela
10                Packer

区号是唯一的。 我希望能够在“代表代码”中列出任何打字错误。例如:区号7是唯一的,但在excel2中,我的名字与Excel1不同。 同时,我想列出excel1中的行,而不是excel2中的行,反之亦然

我已经写了下面的代码,但无法达到我的要求。任何帮助都将不胜感激。谢谢大家!

import openpyxl as xl

wb1 = xl.load_workbook('Excel1.xlsx')
sheet1 = wb1['Sheet 1']


wb2 = xl.load_workbook('Excel2.xlsx')
sheet2 = wb2['Sheet 1']


for row1 in range(2, sheet1.max_row + 1):
    cell1 = sheet1.cell(row1, 2)
    for row2 in range(2, sheet2.max_row + 1):
        cell2 = sheet2.cell(row2, 2)
        if cell1.value == cell2.value:
            print(f' {cell1.value}, {cell2.value}')

Tags: namevaluecodeareapammikesheet1openpyxl
1条回答
网友
1楼 · 发布于 2024-09-29 06:23:08

将ur数据加载到dicts:

dict1 = dict()
dict2 = dict()
for row in range(2, sheet1.max_row+1):
    if sheet1['A{}'.format(row)].value:
        dict1[sheet1['A{}'.format(row)].value] = sheet1['B{}'.format(row)].value
for row in range(2, sheet2.max_row+1):
    if sheet2['A{}'.format(row)].value:
        dict2[sheet2['A{}'.format(row)].value] = sheet2['B{}'.format(row)].value

现在你可以从这两条格言中得到你想要的:

diff_set_not_in_excel2 = dict1.keys() - dict2.keys()
diff_set_not_in_excel1 = dict2.keys() - dict1.keys()

intersection_set = dict1.keys() & dict2.keys()
for key in intersection_set:
    if dict1[key] != dict2[key]:
        print(dict1[key], dict2[key])

当然,u也可以从difference_set的键中获取Representative_Name

相关问题 更多 >