Python Excel突出显示细胞差异 [英] Python Excel Highlight Cell Differences

查看:152
本文介绍了Python Excel突出显示细胞差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

序言:我是新人,自学。这是我的第一个编码项目。我知道这太可怕了一旦它完成和工作,我将重写它。



我正在尝试编写一个python脚本,将比较2个excel文件,并突出显示不同的单元格。我可以打印出差异(使用大熊猫)并突出显示一个单元格(仅通过硬编码特定的单元格)。我不知道如何根据印刷差异来突出显示单元格。

  df1 = pd.read_excel(mxln)#加载主xlsx进行比较
df2 = pd.read_excel(sfcn)#加载学生xlsx进行比较
print('如果NaN,正确,如果不是NaN,不正确')
difference = df2 [ df2!= df1]#扫描差异
打印(差异)

lmfh = load_workbook(mxln)#加载mxln为高亮显示
lsfh = load_workbook(sfcn)#加载sfcn为突出显示
lmws = lmfh.active
lsws = lsfh.active

redFill = PatternFill(start_color ='FFEE1111',end_color ='FFEE1111',fill_type ='solid')
lsws ['A1']。fill = redFill#硬编码单元格颜色
lsfh.save(sfcn)

这只是我被困在的代码的一部分。如果有必要,我可以发布其余的。

解决方案

您可以使用该样式在熊猫的数据框中添加突出显示。

  df2.style.apply(highlight_differences)

然后你可以编写一个设置突出显示标准的函数

  def highlight_differences():
#检查差异
return ['background-color:yellow']


preface: I'm new and self taught. This is my first coding project. I know it's terrible. I'm going to rewrite it once it's complete and working.

I'm trying to write a python script that will compare 2 excel files and highlight the cells that are different. I can print out the differences (using pandas) and highlight a cell (only by hard coding a specific cell). I can't figure out how to highlight cells based on the printed out differences.

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)

This is only the part of the code I'm stuck on. I can post the rest if necessary.

解决方案

You can use the style to add highlighting to your dataframe in pandas.

df2.style.apply(highlight_differences)

Then you can write a function which sets the highlighting criteria

def highlight_differences():
    # check for differences here
    return ['background-color: yellow']

这篇关于Python Excel突出显示细胞差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆