I've just upgraded from openpyxl 1.6.2 to 2.02, and have a question regarding setting cell colors.
The Styles function should handle all the necessary formatting, and that includes using the Fill function to set the cell color. This latter function has fill_type as one of its arguments. How do you set this to a solid fill? In previous versions, this was done using something like:
mycell.style.fill.fill_type = Fill.FILL_SOLID
The documentation, which looks like it's in progress, seems to suggest that setting fill_type = Fill.FILL_SOLID will do the trick (scroll down to the notes at the bottom of the page). But I'm getting an AttributeError when trying it.
from openpyxl.styles import Fill, Color
from openpyxl.styles.colors import RED
redfill = Fill(fill_type=Fill.FILL_SOLID,start_color=RED)
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
redfill = Fill(fill_type=Fill.FILL_SOLID,start_color=RED)
AttributeError: type object 'Fill' has no attribute 'FILL_SOLID'
Any thoughts?
A style is immutable once created, you have to construct a new one and assign it to the cell style
property like this:
mycell.style = Style(fill=PatternFill(patternType='solid', fgColor=Color('FFFF0000')))
this will turn the cell red.
Constants are now module and not class constants.
from openpyxl.styles import fills, PatternFill
fill = PatternFill(patternType=fills.FILL_SOLID)
Though I think it's easier just to use patternType='solid'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With