openpyxl:有条件地使用COUNTIF进行格式化

问题描述 投票:0回答:1

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

    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工作表中?

python openpyxl conditional-formatting
1个回答
0
投票

原来您不能使用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)
© www.soinside.com 2019 - 2024. All rights reserved.