简体   繁体   中英

Python openpyxl conditional format containsText

I all.

I have this code. I need to add conditional format at the cells, the code working with numbers, but not with texts. With texts or haven't effect or generate errors on file open

import pandas as pd
from openpyxl import formatting, styles
from openpyxl.formatting.rule import ColorScaleRule, CellIsRule, FormulaRule, Rule
from openpyxl.styles.differential import DifferentialStyle



df = pd.DataFrame({"Name": ['A', 'B', 'C', 'D', 'E'], 
"Status": ['SUCCESS', 'FAIL', 'SUCCESS', 'FAIL', 'FAIL'],
"Value": [10, 15, 20, 25, 30]})


writer = pd.ExcelWriter('C:\\Users\\emarmis\\OneDrive - Ericsson AB\\WORK\\DEV\\PYTHON\\Ferie\\test.xlsx', engine='openpyxl')
df.to_excel(writer, 'TEST', startrow=1, startcol=1)

wb  = writer.book
ws = writer.sheets['TEST']

red_color = 'ff0000'
yellow_color = 'ffff00'
red_fill = styles.PatternFill(start_color=red_color, end_color=red_color, fill_type='solid')
yellow_fill = styles.PatternFill(start_color=yellow_color, end_color=yellow_color, fill_type='solid')

# This not working
rule = Rule(type='containsText', operator='containsText', text='"FAIL"')
#rule = Rule(type='containsText', operator='containsText', text='FAIL') # same problem with or without double quote on text
rule.dfx = DifferentialStyle(fill=red_fill)
ws.conditional_formatting.add('D3:D7', rule)

# This generate error at the file open
#ws.conditional_formatting.add('D3:D7', formatting.rule.CellIsRule(operator='containsText', formula=['FAIL'], fill=red_fill))

ws.conditional_formatting.add('E3:E7', formatting.rule.CellIsRule(operator='lessThan', formula=['20'], fill=red_fill))
ws.conditional_formatting.add('E3:E7', formatting.rule.CellIsRule(operator='greaterThan', formula=['25'], fill=yellow_fill))


wb.close()
writer.save()

This is the result of the code above

在此处输入图像描述

Any suggestions?

Regards, Marco

Dont know if this helps but it worked for me. Thou i cant get additional conditions to work. String 'c-tur' gets red text with a another red fill:

red_text = Font(color="9C0006")
red_fill = PatternFill(bgColor="FFC7CE")
dxf_c = DifferentialStyle(font=red_text, fill=red_fill)
rule_c = Rule(type="containsText", operator="containsText", text="c-tur", dxf=dxf_c)
rule_c.formula = ['NOT(ISERROR(SEARCH("c-tur",B2)))']
ws.conditional_formatting.add('B2:'+column_name+str(antal_kolumn), rule_c)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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