Fill cells with colors using openpyxl?

I am currently using openpyxl v2.2.2 for Python 2.7 and i wanted to set colors to cells. I have used the following imports

import openpyxl,
from openpyxl import Workbook
from openpyxl.styles import Color, PatternFill, Font, Border
from openpyxl.styles import colors
from openpyxl.cell import Cell

and the following is the code I tried using:

wb = openpyxl.Workbook()
ws = wb.active

redFill = PatternFill(start_color='FFFF0000',
                   end_color='FFFF0000',
                   fill_type='solid')

ws['A1'].style = redFill

but I get the following error:

Traceback (most recent call last)
  self.font = value.font.copy()
AttributeError: 'PatternFill' object has no attribute 'font'

Any idea on how to set cell A1 (or any other cells) with colors using openpyxl?


I believe the issue is that you're trying to assign a fill object to a style.

ws['A1'].fill = redFill should work fine.


The API for styles changed once again. What worked for me was

my_red = openpyxl.styles.colors.Color(rgb='00FF0000')
my_fill = openpyxl.styles.fills.PatternFill(patternType='solid', fgColor=my_red)
cell.fill = my_fill

Color is an alpha RGB hex color. You can pass it in as 'rrggbb' with a default alpha of 00 or specify the alpha with 'aarrggbb'. A bunch of colors are defined as constants in openpyxl.styles.colors if you need to grab one quickly.


This worked for me. They changed things and most of the help you see on the internet is for older versions of the openpyxl library from what I am seeing.

# Change background color 
xls_cell.style = Style(fill=PatternFill(patternType='solid',
                                        fill_type='solid', 
                                        fgColor=Color('C4C4C4')))

in python 3.x

wb = openpyxl.Workbook()
ws = wb.active
redFill = PatternFill(start_color='FFFF0000',
                   end_color='FFFF0000',
                   fill_type='solid')
ws['A1'].fill = redFill

that working but i dont know in python 2.x i hope working just put ws['A1'].fill=redFill