XLWT : Changing the Cell Background Color

5,392 views
Skip to first unread message

Chanman

unread,
Jun 19, 2008, 12:23:22 PM6/19/08
to python-excel
How does one change the cell background color using the xlwt module?
I've looked at several tutorials but none show how to change the
background color. I've tried the following:

badBG = xlwt.Pattern()
badBG.SOLID_PATTERN = 0x34
badBG.NO_PATTERN = 0x34
badBG.pattern_fore_colour = 0x34
badBG.pattern_back_colour = 0x34

badFontStyle = xlwt.XFStyle()
badFontStyle.Pattern = badBG

sheet1.write(1,1,'hello world', badFontStyle)

However, the background cell color still remains white. Any help?

John Machin

unread,
Jun 19, 2008, 6:55:37 PM6/19/08
to python-excel
On Jun 20, 2:23 am, Chanman <bryancc...@gmail.com> wrote:
> How does one change the cell background color using the xlwt module?
> I've looked at several tutorials but none show how to change the
> background color. I've tried the following:
>
> badBG = xlwt.Pattern()
> badBG.SOLID_PATTERN = 0x34
> badBG.NO_PATTERN = 0x34

Python convention is that UPPER_CASE is used for pseudo-constants --
assigning different values to them is at best pointless and at worst
could make things blow up.

You need
badBG.pattern = badBG.SOLID_PATTERN
to set what type of pattern you want. The default is NO_PATTERN.

> badBG.pattern_fore_colour = 0x34
> badBG.pattern_back_colour = 0x34

Setting pattern_back_colour is neither necessary nor useful for a
SOLID_PATTERN -- you only see the pattern_fore_colour. On the other
hand, for any other pattern type, you need to set pattern_fore_colour
and pattern_back_colour to two different colours; if they are the
same, you would get the same effect as SOLID_PATTERN.

>
> badFontStyle = xlwt.XFStyle()

"Font" is irrelevant and/or potentially misleading here -- but I
should address my grumble to the author of the blog from which you
copied this :-)

> badFontStyle.Pattern = badBG
>
> sheet1.write(1,1,'hello world', badFontStyle)
>
> However, the background cell color still remains white. Any help?

HTH,
John

Chanman

unread,
Jun 23, 2008, 12:36:22 PM6/23/08
to python-excel
Yes, it did, thank you. For those that didn't quite follow, the code
below (perhaps not the most elegant) makes a style with a green cell
background:

badBG = xlwt.Pattern()
badBG.pattern = badBG.SOLID_PATTERN
badBG.pattern_fore_colour = 3

badFontStyle = xlwt.XFStyle()
badFontStyle.pattern = badBG

Bryan
Reply all
Reply to author
Forward
0 new messages