简体   繁体   English

如何在 Python 中使用 xlsxwriter 将条件格式应用于整个工作表?

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

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.我正在尝试使用 xlsxwriter 在 Python 中应用条件格式,但我不确定如何引用整个工作表而不仅仅是一系列单元格。 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.使用这个条件格式规则,我基本上是想说单元格是否小于其左侧的单元格,然后应用格式 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:我要更改的是 $1:$1048576 因为这不是引用整个工作表而是给我一条错误消息:

ValueError: invalid literal for int() with base 10: '$1:$1048576' ValueError: int() 以 10 为底的无效文字:'$1:$1048576'

Thank you in advance for the help!提前感谢您的帮助!

To apply the conditional format to the entire worksheet you can use the range A1:XFD1048576 .要将条件格式应用于整个工作表,您可以使用范围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.我不知道 Excel 是否允许“小于”标准成为公式。 That usually needs to be added as a 'formula' criteria type in Excel.这通常需要作为“公式”标准类型添加到 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).此外,条件格式中的OFFSET(INDIRECT..)引用通常可以使用更简单的公式来实现,您可以使用 Excel 绝对运算符$来约束行或列(在上面的文档中也有解释)。 Anyway you should double check that this conditional format works in Excel first before transferring it to XlsxWriter.无论如何,在将其传输到 XlsxWriter 之前,您应该首先仔细检查此条件格式在 Excel 中是否有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM