使用 openpyxl by text 的简单条件文本格式

Simple conditional text formatting with openpyxl by text

我正在使用 openpyxl 3.0.3 和 python 3.7.3。我不知道我使用的 Excel 是什么版本,因为它似乎没有在任何地方说明。这是 Office 365。

我想做的很简单:如果单元格值为 "fail",则将单元格设为一种颜色,如果 "pass" 为另一种颜色,等等。但我尝试的一切似乎 运行 很好,但是当我尝试使用 Excel 打开工作簿时,它得到相同的结果:Excel 说 "We found a problem with some content" 并提出修复工作簿。当我让它修复时,格式消失了。我已经尝试了以下所有内容,取自各种 SO 答案和其他示例:

cellref = 'B2'
red_font = Font(size=14, bold=True, color='ffffff')
red_fill = PatternFill(start_color='ffcccc', end_color='ffcccc', fill_type='solid')

ws2.conditional_formatting.add(cellref, CellIsRule(operator='equal', formula=['fail'], fill=red_fill, font=red_font))
ws2.conditional_formatting.add(cellref, CellIsRule(operator='containsText', formula=['fail'], fill=red_fill, font=red_font))
ws2.conditional_formatting.add(cellref, CellIsRule(operator='lessThan', formula=['0'], fill=red_fill, font=red_font))
ws2.conditional_formatting.add(cellref, FormulaRule(formula=[f'NOT(ISERROR(SEARCH("fail",{cellref})))'], stopIfTrue=True, fill=red_fill))

所有人都得到了相同的坏结果。我已经阅读了 documentation and examples 以及我能找到的关于该主题的所有 Whosebug 答案。这似乎是包的简单基本用法。

我认为这与您选择的选项组合有关。实际上(在我看来)声明一个 Rule 然后分配一个 type 更容易。你的后两条规则很好。对我来说编译得很好。前两个有问题。我用 'containsText' 类型的 Rule 替换了它们。

根据您提供的示例,我得出以下结论:

cellref = 'B1:B6' #adjusted to show more cells
red_font = Font(size=14, bold=True, color='ffffff')
red_fill = PatternFill(start_color='ffcccc', end_color='ffcccc', fill_type='solid')

ws2.conditional_formatting.add(cellref, Rule(type='containsText', operator='containsText', formula=['fail'], dxf = DifferentialStyle(fill=red_fill, font=red_font)))
ws2.conditional_formatting.add(cellref, CellIsRule(operator='lessThan', formula=['0'], fill=red_fill, font=red_font))
ws2.conditional_formatting.add(cellref, FormulaRule(formula=[f'NOT(ISERROR(SEARCH("fail",{cellref})))'], stopIfTrue=True, fill=red_fill))

结果

尽管@APhillips 提供了有用的答案,但我在文本搜索条件方面遇到了问题。

我上班最棒的事情是:

from openpyxl import styles, formatting

cellref  = 'B1:B6' #adjusted to show more cells
red_fill = styles.PatternFill(start_color='ffcccc', end_color='ffcccc', fill_type='solid')

rule = formatting.Rule(type='expression')

rule.formula = [f'ISNUMBER(SEARCH("fail", {cellref}))']
rule.dxf     = styles.differential.DifferentialStyle(fill=red_fill)

sheet_object.conditional_formatting.add(cellref, rule)