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.
From the documentation:
from openpyxl.styles import PatternFill
sheet['A1'].fill = PatternFill(bgColor="FFC7CE", fill_type = "solid")
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With