我有一个我用openpyxl生成的电子表格,其中包含许多系统检查。根据规则;在我的电子表格中将单词Pass,Fail或Informational插入E列。我想使用Openpyxl根据Pass或Fail的值有条件地格式化电子表格的填充。像Green for Pass和Red for Fail这样的东西。
我目前的openpyxl代码是:
wb = Workbook()
ws = wb.active
ws.freeze_panes = ws.cell('A3')
ws.title = 'Best Practice Report for XXX'
ws['A1'] = 'Best Practice Report for XXX %s' % curdate
ws['A2'] = 'IP Address/FQDN'
ws['B2'] = 'BP Number'
ws['C2'] = 'Title'
ws['D2'] = 'Priority'
ws['E2'] = 'Status'
ws['F2'] = 'Description'
a1 = ws['A1']
a1.font = Font(size=20)
redFill = PatternFill(start_color='FFEE1111', end_color='FFEE1111', fill_type='solid')
ws.conditional_formatting.add('E4:E1000', FormatRule(text=['Fail'], stopIfTrue=True, fill=redFill))
wb.save('bp--TESTresults.xlsx')
我的问题是条件格式规则,我找不到基于单元格中文本的条件格式的任何好例子。
更新
感谢查理克拉克斯的回应我得到了这个工作。创建了两个规则如下。
ws.conditional_formatting.add('E4:E1000', FormulaRule(formula=['NOT(ISERROR(SEARCH("Pass",E4)))'], stopIfTrue=True, fill=greenFill))
ws.conditional_formatting.add('E4:E1000', FormulaRule(formula=['NOT(ISERROR(SEARCH("Fail",E4)))'], stopIfTrue=True, fill=redFill))
答案 0 :(得分:4)
我只是掀起了一个档案并做了一些反省。它具有A2中的值:A5我认为这应该可以帮助你:
from openpyxl import load_workbook
wb = load_workbook("Issues/cf.xlsx")
ws = wb.active
ws.conditional_formatting.cf_rules
{'A2:A5': [<openpyxl.formatting.rule.Rule object at 0x108e6dfd0>]}
rule = _['A2:A5']
rule = rule[0]
rule.type
'containsText'
rule.formula
['NOT(ISERROR(SEARCH("fail",A2)))']
rule.stopIfTrue
None
rule.operator
'containsText'