How do I apply conditional formatting to an entire sheet using xlsxwriter in Python?

Viewed 41

I am trying to apply conditional formatting in Python using xlsxwriter, but am unsure of how to reference the entire sheet instead of just a range of cells. I need the sheet to be referenced as opposed to a set range of cells so that when the data frame auto updates with new data, that new data will still be captured in the conditional formatting rule. The data frame just captures daily stock prices.

With this conditional formatting rule I am basically trying to say if the cell is less than the cell to the left of it, then apply format 1.

Here is what I was trying:

worksheet1.conditional_format('$1:$1048576', {'type': 'cell',
                                             'criteria': 'less than',
                                              'value' : 'OFFSET(INDIRECT(ADDRESS(ROW(), 
                                                          COLUMN())),0,-1)',
                                              'format': format1})

What I am trying to change is the $1:$1048576 as this is not referencing the entire sheet but instead giving me an error message:

ValueError: invalid literal for int() with base 10: '$1:$1048576'

Thank you in advance for the help!

1 Answers

To apply the conditional format to the entire worksheet you can use the range A1:XFD1048576. Something like this:

worksheet1.conditional_format('A1:XFD1048576',
                              {'type': 'cell',
                               'criteria': 'less than',
                               'value' : 'OFFSET(INDIRECT(ADDRESS(ROW(), COLUMN())),0,-1)',
                               'format': format1})

See the Row and Column Ranges section of the docs.

However, the conditional format doesn't look right. I don't know if Excel allows the 'less than' criteria to be a formula. That usually needs to be added as a 'formula' criteria type in Excel. Also, OFFSET(INDIRECT..) references in Conditional Formats can often be achieved using a simpler formula where you constrain the row or column with the Excel absolute operator $ (which is also explained in the docs above). Anyway you should double check that this conditional format works in Excel first before transferring it to XlsxWriter.

Related