Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cell Colors Using OpenPyxl 2.02

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?

like image 858
user3666221 Avatar asked May 22 '14 18:05

user3666221


2 Answers

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.

like image 119
Mike Avatar answered Sep 21 '22 20:09

Mike


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'

like image 33
Charlie Clark Avatar answered Sep 24 '22 20:09

Charlie Clark