Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a background color to Cell OpenPyXL

I'm trying to make it where my code gives off a Green background on cell when it is "Present" and a Red background on cell if it is "Absent". Here is my code.

ws1.cell(column=1, row=t, value="%s" % blue_student_list)
if (student_check(i)):
    ws1.cell(column=2, row=t, value="%s" % "Present")
else:
    ws1.cell(column=2, row=t, value="%s" % "Absent")

This code works flawlessly, I'm just wondering how I can add in the background color behind the cell.

like image 222
Dylan Avatar asked Mar 10 '16 13:03

Dylan


2 Answers

From the documentation:

from openpyxl.styles import PatternFill
        
sheet['A1'].fill = PatternFill(bgColor="FFC7CE", fill_type = "solid")
    
like image 137
Avik Samaddar Avatar answered Sep 21 '22 09:09

Avik Samaddar


As @Charlie Clark (co-author of openpyxl) suggests, Conditional formatting might be a better way to go. More information in the official doc

If you want to change the background color, from more recent versions, keyword bgcolor seems not to work (in my case, it the color of the cell ends up black).

Instead, you can use start_color or fgColor. For example, both solutions work:

from openpyxl.styles import PatternFill
from openpyxl.styles.colors import YELLOW

sheet['A1'].fill = PatternFill(start_color="FFC7CE", fill_type = "solid")
sheet['A1'].fill = PatternFill(fgColor=YELLOW, fill_type = "solid")
like image 41
Jean-Francois T. Avatar answered Sep 21 '22 09:09

Jean-Francois T.