Question

I'm working with an Excel spreadsheet in Python. I want to change the background color of an entire row if a condition is not respected. However, after running my code, only the background color of the empty cells of the rows (the one not containing any character) is changed. My first 9 columns contain information and my code only changes the background color from column J to Z.

from xlrd import open_workbook
from xlwt import Workbook, easyxf
Error_Style = easyxf('pattern: pattern solid, fore_colour red;',)

[...]

else:
w_sheet.row(row_index).set_style(Error_Style)

[...]

I was wondering if I am using the wrong pattern with easyxf.

Was it helpful?

Solution

Whenever you write a cell using xlwt, you write not only the value but also the style for that cell, which overrides any previous styling in that cell. You unfortunately can't just "inherit" the row styling. For now, the way to achieve what you want is to create styles that you will use when writing to the affected rows, and include those styles at the same time that you are writing the values.

For example, I have a report in which the backgrounds are supposed to alternate between white and gray. Though I'd like to just set all the even-numbered rows to gray independently of the values, instead I have to have a pair of styles, and choose the appropriate one at the appropriate time. It goes something like this:

styles = (easyxf(), easyxf('pattern: pattern solid, fore_color gray25'))

for rx, record in enumerate(records, start=1):
    style = styles[rx % 2]  # Do your own conditional style selection here
    for cx, value in enumerate(record):
        ws.write(rx, cx, value, style)

In actuality, I have more than just one pair of styles, I have several pairs. (Various different columns have different numeric formats, some percentages, some dates, etc.) So for my own case, it's even more complicated than what I've shown above. But hopefully, this illustrates what I mean by "choose the appropriate style at the appropriate time".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top