I'm trying to change the background color of a cell according to its text using IF and Patternfill from Openpyxl but I'm receiving a type error. See bellow the code:
#Level - Replied Travel Alerts(RTA)
incident_index = item.body.index("incident") 12
category_indexpos = item.body[incident_index:].index("Category") incident_index
level = item.body[incident_index:category_indexpos]
ws.cell(row=index 2, column = 2).value = level
if "Advisory" in level:
advisory_pattern = Pattern(patternType = "solid", fgColor="FFFF00")
ws.cell(row=index 2, column = 2).fill = advisory_pattern
elif "Notice" in level:
notice_pattern = Pattern(patternType = "solid", fgColor = "00B050")
ws.cell(row=index 2, column = 2).fill = notice_pattern
elif "Special" in level:
special_pattern = Pattern(patternType = "solid", fgColor= "FF0000")
ws.cell(row=index 2, column = 2).fill = special_pattern
but I'm getting an error on the "advisory_pattern = Pattern(patternType = "solid", fgColor="FFFF00")" line. See the message:
Exception has occurred: TypeError cannot create 're.Pattern' instances
Can anyone help me?
Thanks
CodePudding user response:
Well, re.Pattern is from the python re library, which has nothing to do with creating background fills in Openpyxl
First, I would use this import at the top of your code:
from openpyxl.styles import fills
Then you can modify your lines to fit this format (I used your first fill as my example):
ws.cell(row=index 2, column = 2).fill = fills.PatternFill("solid", fgColor="FFFF00")
If you want to store your fills in variables still, just make sure you are using fill objects from the openpyxl fills library and not Pattern objects from the python re library.