【发布时间】:2015-07-10 04:19:47
【问题描述】:
我有一个使用 openpyxl 生成的电子表格,其中包含许多系统检查。基于规则; Pass、Fail 或 Informational 这三个词被插入到我的电子表格的 E 列中。我想使用 Openpyxl 根据通过或失败的值有条件地格式化电子表格的填充。类似绿色表示通过,红色表示失败。
我当前的 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))
【问题讨论】:
-
我很想对现有文件使用内省。从 openpyxl 2.2 开始,规则在 Excel 看到它们时公开。我同意文档可能会更好,但我个人对条件格式的经验很少。
标签: python python-2.7 openpyxl