简体   繁体   English

使用openpyxl基于文本进行条件格式化

[英]Conditional Formatting with openpyxl based on text

I have a spreadsheet that I am generating with openpyxl that contains a number of system checks. 我有一个用openpyxl生成的电子表格,其中包含许多系统检查。 Based on the rules; 根据规则; the words Pass, Fail or Informational are inserted into Column E in my spreadsheet. 在我的电子表格的E列中插入了“通过”,“失败”或“信息性”字样。 I would like to use Openpyxl to conditionally format the fill of the spreadsheet based on the value of Pass or Fail. 我想使用Openpyxl根据Pass或Fail的值有条件地格式化电子表格的填充。 Something like Green for Pass and Red for Fail. 诸如绿色表示通过,红色表示不通过。

My current code for openpyxl is: 我当前的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') 

My issue is with the conditional formatting rule, I cannot find any good examples for conditional formatting based on the text in a cell. 我的问题是条件格式设置规则,我找不到基于单元格中文本的任何很好的条件格式设置示例。

Update 更新资料
Thanks to Charlie Clarks response I got this working. 感谢Charlie Clarks的回应,我终于做到了。 Created two rules as follows. 创建了两个规则,如下所示。

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))

I just whipped up a file and did some introspection. 我只是整理了文件并进行了一些自省。 It has values in A2:A5 I think this should help you along: 它在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'

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

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