openpyxl:使用 COUNTIF 的条件格式

openpyxl: conditionally formatting with COUNTIF

我正在使用 openpyxl 创建一个 Excel sheet,我需要根据是否在单元格中找到某个文本字符串来有条件地设置格式。例如,我想查看一个单元格是否以 "ok:" 开头,所以我的等式是 =COUNTIF(A1,"ok:*")>0。这适用于 Excel。但是,openpyxl 中的以下 Python 代码导致 Excel 表示 sheet 已损坏:

redFill = PatternFill(start_color='EE1111', end_color='EE1111', fill_type='solid')
ws.conditional_formatting.add('E1:E10', FormulaRule(formula=['=COUNTIF(A1,"ok:*")>0'],fill=redFill))

如何使用 openpyxl 将 COUNTIF 条件正确添加到 excel sheet?

原来你不能使用COUNTIF。这是有效的代码:

red_text = Font(color="9C0006")
red_fill = PatternFill(bgColor="FFC7CE")
dxf = DifferentialStyle(font=red_text, fill=red_fill)
rule = Rule(type="containsText", operator="containsText", text="highlight", dxf=dxf)
rule.formula = ['NOT(ISERROR(SEARCH("ok:*",A1)))']
wsNonDebug.conditional_formatting.add('A1:F40', rule)