简体   繁体   English

如何在 openpyxl 中应用条件格式?

[英]How to apply conditional formatting in openpyxl?

I am using openpyxl to manipulate a Microsoft Excel Worksheet.我正在使用openpyxl来操作 Microsoft Excel 工作表。

What I want to do is to add a Conditional Formatting Rule that fills the rows with a given colour if the row number is even, leaves the row blank if not.我想要做的是添加一个条件格式规则,如果行号是偶数,则用给定的颜色填充行,如果不是,则将行留空。

In Excel this can be done by selecting all the worksheet, creating a new formatting rule with the text =MOD(ROW();2)=0 or =EVEN(ROW()) = ROW() .在 Excel 中,这可以通过选择所有工作表,使用文本=MOD(ROW();2)=0=EVEN(ROW()) = ROW()创建新的格式规则来完成。

I tried to implement this behaviour with the following lines of code (considering for example the first 10 rows):我尝试使用以下代码行来实现此行为(例如考虑前 10 行):

redFill = PatternFill(start_color='EE1111', end_color='EE1111', fill_type='solid')
ws2.conditional_formatting.add('A1:A10', FormulaRule(formula=['MOD(ROW();2) = 0'], stopIfTrue=False, fill=redFill))

My program runs correctly but when I try to open the output Excel file, it tells me that the file contains unreadable content and it asks me if I want to recover the worksheet content.我的程序运行正常,但是当我尝试打开输出 Excel 文件时,它告诉我该文件包含不可读的内容,并询问我是否要恢复工作表内容。 By clicking yes, the worksheet is what I expect but there is no formatting.通过单击是,工作表是我所期望的,但没有格式。

What is the correct way to apply such a formatting in openpyxl (possibly to the entire worksheet)?在 openpyxl(可能应用于整个工作表)中应用这种格式的正确方法是什么?

Unfortunately, the way formulae are handled in conditional formatting is particularly opaque.不幸的是,在条件格式中处理公式的方式特别不透明。 The best thing to do is to create a file with the relevant conditional format and inspect the relevant file by unzipping it.最好的办法是创建一个具有相关条件格式的文件,并通过解压缩来检查相关文件。 The rules are stored in the relevant worksheet files and the formats in the styles file.规则存储在相关工作表文件中,格式存储在样式文件中。

However, I suspect that the problem may simply because you are using ";"但是,我怀疑问题可能仅仅是因为您使用的是“;” to separate parameters in the function: you must always use commas for this.分隔函数中的参数:您必须始终为此使用逗号。

A sample formula from one of my projects:来自我的一个项目的示例公式:

green_text = Font(color="006100")
green_fill = PatternFill(bgColor="C6EFCE")
dxf2 = DifferentialStyle(font=green_text, fill=green_fill)
r3 = Rule(type="expression", dxf=dxf2)
r3.formula = ["AND(ISNUMBER(C2), C2>=400)"]

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

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