简体   繁体   English

为什么我的 xlsxwriter 条件格式不起作用?

[英]Why is my xlsxwriter conditional formatting not working?

I have two columns in a dataframe named FirstName and LastName.我在 dataframe 中有两列名为 FirstName 和 LastName。

I need to make the font color of any cell's text in the FirstName column red if any cell in the LastName is not blank.如果 LastName 中的任何单元格为空,我需要将 FirstName 列中任何单元格文本的字体颜色设置为红色。

writer = pd.ExcelWriter(fileName, engine='xlsxwriter')
df.to_excel(writer,'Sheet1', index_label=None, index=False)
workbook  = writer.book
redFont   = workbook.add_format({'font_color': '#9C0006'})
worksheet = writer.sheets['Sheet1']
worksheet.conditional_format(1, 0, 9999999, 0,
                             {'type':     'formula',
                              'criteria': '=ISBLANK($B1)',
                              'format':   redFont})
writer.save()

I do not get errors but the font color does not change.我没有收到错误,但字体颜色没有改变。 I can not figure out what I am doing wrong.我不知道我做错了什么。 Any ideas?有任何想法吗?

Thank you!谢谢!

There are a couple of small errors in the code: the range is bigger than the maximum range allowed by Excel (so XlsxWriter rejects the conditional format) and also if the range starts in cell A2 you should apply the conditional format using the reference cell $B2 .代码中有几个小错误:范围大于 Excel 允许的最大范围(因此 XlsxWriter 拒绝条件格式)并且如果范围从单元格A2开始,您应该使用参考单元格$B2应用条件格式$B2 Also I think the logic should be reversed to match cells that are not blank另外我认为应该反转逻辑以匹配非空白的单元格

It should be something like this:它应该是这样的:

import pandas as pd

fileName = 'test.xlsx'

df = pd.DataFrame({'FirstName': ['Anna', 'Bob', 'Cian', 'Dora'],
                   'LastName':  ['Aran', '',    '',     'Dodd']})

writer = pd.ExcelWriter(fileName, engine='xlsxwriter')
df.to_excel(writer, 'Sheet1', index_label=None, index=False)

workbook = writer.book
redFont = workbook.add_format({'font_color': '#9C0006'})
worksheet = writer.sheets['Sheet1']

worksheet.conditional_format(1, 0, 1048575, 0,
                             {'type':     'formula',
                              'criteria': '=ISBLANK($B2)=FALSE',
                              'format':   redFont})
writer.save()

Output : Output :

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM