Fill cells with colors using openpyxl?

PythonOpenpyxl

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

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

Solution 2 - Python

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.

Solution 3 - Python

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')))

Solution 4 - Python

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

Solution 5 - Python

What I would do for Excel is this:

from openpyxl import Workbook, load_workbook
from openpyxl.styles import PatternFill

wb = load_workbook("test.xlsx")
ws = wb.active

ws["A1"].fill = PatternFill("solid", start_color="FFA500")

You can replace "A1" with another cell and start_color has to be a hex color.

Solution 6 - Python

To fill a range of rows/columns, do this

for cell in ws['A1:A100']:
   cell[0].fill = redFill

To fill all rows of a column

for cell in ws['A1:{}'.format(ws.max_row)]:
   cell[0].fill = redFill

Solution 7 - Python

from openpyxl import Workbook, load_workbook
from openpyxl.styles import PatternFill

_file_name = "Test.xlsx"
_sheet_name = "Test_Sheet"

def new_workbook(_file_name, _sheet_name):
    wb = Workbook()  # Workbook Object
    ws = wb.active  # Gets the active worksheet
    ws.title = _sheet_name  # Name the active worksheet

    # Writing the header columns
    ws['A1'] = 'Name'
    ws['B1'] = 'Class'
    ws['C1'] = 'Section'
    ws['D1'] = 'Marks'
    ws['E1'] = 'Age'
    

    col_range = ws.max_column  # get max columns in the worksheet

    # formatting the header columns, filling red color
    for col in range(1, col_range + 1):
        cell_header = ws.cell(1, col)
        cell_header.fill = PatternFill(start_color='FF0000', end_color='FF0000', fill_type="solid") #used hex code for red color

    wb.save(_file_name)  # save the workbook
    wb.close()  # close the workbook

if __name__ == '__main__':
new_workbook(_file_name, _sheet_name)

Result - enter image description here

Solution 8 - Python

Use a nested for loop to fill a two dimensional range.

Python 3.9

import openpyxl as op
fill_gen = op.styles.PatternFill(fill_type='solid',
                                 start_color='FFFFFF',
                                 end_color='FFFFFF')
for row in ws["A1:BB50"]:
    for cell in row:
        cell.fill = fill_gen

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAhmed RashadView Question on Stackoverflow
Solution 1 - PythonCharlie ClarkView Answer on Stackoverflow
Solution 2 - PythonldrgView Answer on Stackoverflow
Solution 3 - PythonM T HeadView Answer on Stackoverflow
Solution 4 - PythonismailView Answer on Stackoverflow
Solution 5 - Pythontuurtje11View Answer on Stackoverflow
Solution 6 - PythonUmair AyubView Answer on Stackoverflow
Solution 7 - PythonRITA KUSHWAHAView Answer on Stackoverflow
Solution 8 - PythonRK ReplogleView Answer on Stackoverflow