user3120960
user3120960

Reputation: 179

openpyxl (2.4.8) trouble with background in style; always black

I recently switched my code to openpyxl to take advantage of the the ability to update workbooks and I'm having trouble with the background style. I've tried a couple variations of the code below using both colors and the hex values and I always get the same results which is a black background and bold white text. Thanks in advance!

from openpyxl.styles import NamedStyle, PatternFill, Border, Side, 
Alignment, Protection, colors, Font

styl_hdg = NamedStyle(name="styl_hdg")

styl_hdg.font = Font(color=colors.WHITE, bold=True)
styl_hdg.alignment = Alignment(wrap_text=True)
styl_hdg.fill = PatternFill(bgColor=colors.DARKGREEN, fill_type="solid")

ws.cell(row=myrow, column=mycol).style = styl_hdg

I have also tried this because sometimes I get and error style already defined. When I go to add rows to an existing workbook/worksheet.

ws.cell(row=myrow, column=mycol).font = Font(bold=True,color=colors.WHITE)
    ws.cell(row=myrow, column=mycol).fill = 
PatternFill(fill_type="solid",bgColor=colors.DARKGREEN)

Upvotes: 4

Views: 5360

Answers (2)

Thanks to Pedroski55: https://python-forum.io/Thread-Best-way-to-set-cell-background-colour-in-openpyxl

from openpyxl import Workbook
from openpyxl.styles import PatternFill

xlsx = Workbook()

xlsx['Sheet']['A1'].fill = PatternFill(start_color='FF001F', end_color='FF001F', 
fill_type = 'solid')
xlsx.save('some.xlsx')

Upvotes: 2

Charlie Clark
Charlie Clark

Reputation: 19497

From the OOXML specification:

This element is used to specify cell fill information for pattern and solid color cell fills. For solid cell fills (no pattern), fgColor is used.

So you need to set the fgColor

Upvotes: 8

Related Questions