Python Excel突出显示细胞差异
问题描述:
前言:我是新人,自学成才。这是我的第一个编码项目。我知道这太可怕了。一旦它完成并工作,我将重写它。Python Excel突出显示细胞差异
我想写一个python脚本,将比较2个excel文件,并突出显示不同的单元格。我可以打印出差异(使用熊猫)并突出显示一个单元格(仅通过硬编码特定单元格)。我无法弄清楚如何根据打印出的差异来突出显示单元格。
df1 = pd.read_excel(mxln) # Loads master xlsx for comparison
df2 = pd.read_excel(sfcn) # Loads student xlsx for comparison
print('If NaN, correct. If not NaN, incorrect')
difference = df2[df2 != df1] # Scans for differences
print(difference)
lmfh = load_workbook(mxln) # Load mxln for highlight
lsfh = load_workbook(sfcn) # Load sfcn for highlight
lmws = lmfh.active
lsws = lsfh.active
redFill = PatternFill(start_color='FFEE1111', end_color='FFEE1111', fill_type='solid')
lsws['A1'].fill = redFill # Hardcoded cell color
lsfh.save(sfcn)
这只是我卡在代码的一部分。如有必要,我可以发布其余的内容。
答
您可以使用该样式向pandas中的数据框添加突出显示。
df2.style.apply(highlight_differences)
然后,你可以写一个设置突出标准的函数
def highlight_differences():
# check for differences here
return ['background-color: yellow']