使用openpyxl比较两个Excel文件

时间:2018-08-30 05:23:54

标签: python excel openpyxl

我正在比较两个具有不同行数的Excel文件。我需要在列中搜索特定值。但是我做不到。 因为我是python的新手。 这是我的代码

import openpyxl
from openpyxl import Workbook
wk1= openpyxl.load_workbook("Condition.xlsx")
wk2= openpyxl.load_workbook("Database.xlsx")
sh1 = wk1['Sheet1']
sh2 =wk2['Sheet1']
rows1 = sh1.max_row
columns1 = sh1.max_column
rows2 = sh2.max_row
columns2 = sh2.max_column




 for i in range(2,rows2):
     c = sh1.cell(2,1).value
     if sh2.cell(i,2).value==c:
         if sh2.cell(i,3).value== 'Credit' and sh1.cell(i,3).value=='UWCC_A':
             print(sh2.cell(i,3).value)
         else:    
             print(1)   



Excel1 :

C1    C2   C3       
mike  U_11 Baseball
john  U_12 cricket
sam   U_12 Handball

Excel 2

C1    C2  C4
mike  U_11  ABC
mike  U_11  XYZ
mike  U_11  EUE
mike  U_11  PIJ

1 个答案:

答案 0 :(得分:0)

您也可以使用cell('A2').value

从单元格中读取内容

为单元格着色

from openpyxl.styles import Color, PatternFill, Font, Border, colors

green = (0, 192, 0)

def iter_to_hex(x):

    #X is upper, x is lower
    return ''.join(["{:02X}".format(_) for _ in x])

print(iter_to_hex(green))

fill_green = PatternFill('solid',
                         start_color=iter_to_hex(green),
                         end_color=iter_to_hex(green))

wc = ws.cell(row=_r, column=_c)

 if _res['result']:

    wc.value = 'Something'
    wc.fill = fill_green