1

I'm trying to change the color of my excel spreadsheet to color code data using python's xlwt package. Here's my current code:

from xlrd import open_workbook
from tempfile import Temporary File
from xlwt
import sys
import csv

....
....#Some other code

style = xlwt.XFStyle() #this is the line throwing the error
pattern = xlwt.Pattern()
pattern.pattern = xlwt.Pattern.SOLID_PATTERN
pattern.pattern_fore_colour = xlwt.Style.colour_map['red']

pattern.pattern_fore_colour = xlwt.Style.colour_map['red']
newSheet.write(row, col, values[row - 1][col], pattern)

....
....#Some other code

Other code sections are there because it is a longer script than shown but those sections of code aren't related to this problem

I get the following stack trace when it runs:

Traceback (most recent call last):
   File "excel-procesor.py", line 85, in <module>
        newSheet.write(row, col, values[row - 1][col], pattern)
   File "/usr/local/lib/python2.7/dist-packages/xlwt/Worksheet.py", line 1030, in write self.row(r).write(c, label, style)
   File "/usr/local/lib/python2.7/dist-packages/xlwt/Row.py", line 234, in write self.__adjust_height(style)
   File "/usr/local/lib/python2.7/dist-packages/xlwt/Row.py", line 64, in __adjust_height
        twip = style.font.height
AttributeError: 'Pattern' object has no attribute 'font'

I'm using How to change background color of excel cell with python xlwt library? and python xlwt set custom background colour of a cell as guides.

Community
  • 1
  • 1
avorum
  • 2,243
  • 10
  • 39
  • 49

1 Answers1

1

According to the source code:

xlwt.Worksheet.write(self, r, c, label='', style=<xlwt.Style.XFStyle object at 0x053AEA10>)

write should receive the style as argument, and not directly the Pattern object.

You should try to put your pattern object into style and pass style as argument:

style.pattern = pattern
newSheet.write(row, col, values[row - 1][col], style)

Some examples I found useful how to use xlwt, including how to set the style

Zeugma
  • 31,231
  • 9
  • 69
  • 81