Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 630
Ahmed Rashad Avatar asked May 27 '15 13:05

Ahmed Rashad


People also ask

How do I style a cell in openpyxl?

To change a style property of a cell, first you either have to copy the existing style object from the cell and change the value of the property or you have to create a new style object with the desired settings. Then, assign the new style object to the cell. Save this answer.

What is difference between openpyxl and XlsxWriter?

XlsxWriter vs openpyxl: What are the differences? Developers describe XlsxWriter as "A Python module for creating Excel XLSX files". A Python module for creating Excel XLSX files. On the other hand, openpyxl is detailed as "A Python library to read/write Excel 2010 xlsx/xlsm files".


1 Answers

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

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

like image 96
Charlie Clark Avatar answered Oct 25 '22 19:10

Charlie Clark