簡體   English   中英

想要使用 openpyxl 將 excel 中的兩列與唯一列進行比較

[英]want to compare two columns in excel with unique column using openpyxl

我對 python 很陌生,並且在過去的幾周里一直在學習。 我想將 excel 中的兩列與使用 openpyxl 的唯一列進行比較。

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

區號是唯一的。 我希望能夠列出“Representative_Code”中的任何錯字。 例如:區號 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}')

將您的數據加載到字典:

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])

當然,你也可以從Representative_Name的keys中獲取Conceptor_Name的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM