I have looked into many stackoverflow questions but none of them seemed to solve my problem. I am using Python and Openpyxl to fill a whole row with red given a certain condition. I did all the importations necessary :
from openpyxl.styles import PatternFill, NamedStyle, Color from openpyxl.styles.colors import RED
And my code is the following :
for cell in sheet[i]: cell.style = NamedStyle(fill=PatternFill(patternType='solid', fill_type='solid', fgColor=Color(RED)))
When I ask to print the first occurence of cell it gives me
<Cell 'Divers'.A4>
which is what I am looking for. However, the following error comes every time : “Style Normal exists already”. There is absolutely no cell formatting or style whatsoever in the rest of the code but the Excel file cells are indeed filled with yellow already.
Any idea on how to solve this ? Thanks in advance for any help.
Advertisement
Answer
If using a NamedStyle
, you’re required to pass a name.
red_foreground = NamedStyle( name="RedForeground", fill=PatternFill( patternType='solid', fill_type='solid', fgColor=Color(RED) ) )
Since you’re assigning this NamedStyle
to more than one cell, it makes sense to register it to your workbook.
wb.add_named_style(red_foreground)
Then you can update it’s application to cells, like so:
for cell in sheet[i]: cell.style = "RedForeground"