[英]How do I create an “if and” statement to conditionally format a column of cells using xlsxwriter in Python
This isn't working (obviously), so i'm wondering if there are any suggestions.这不起作用(显然),所以我想知道是否有任何建议。 Thank you.谢谢你。
The goals: - If AA2 > 0 and AB2 < 0, then format cells in column A with formatc3.目标: - 如果 AA2 > 0 且 AB2 < 0,则使用 formatc3 格式化列 A 中的单元格。 - If AA2 < 0 and AB2 > 0, then format cells in column A with formatc3. - 如果 AA2 < 0 且 AB2 > 0,则使用 formatc3 格式化列 A 中的单元格。
worksheet.conditional_format('A2:A2100', {'type': 'formula',
'criteria': '=AND($AA2>0,$AB2<0)',
'format': formatc3})
worksheet.conditional_format('A2:A2100', {'type': 'formula',
'criteria': '=AND($AA2<0,$AB2>0)',
'format': formatc3})
You almost got it right, you miss one small thing in the excel formula, they should start from the first row and not the second.你几乎是对的,你错过了 excel 公式中的一个小东西,它们应该从第一行而不是第二行开始。 Also no need to write two different statements as your conditions could be nested in just one, it's more efficient and readable.也无需编写两个不同的语句,因为您的条件可以嵌套在一个中,它更有效且可读性更高。 In general try to reproduce your desired output manually in excel, then it's easy to convert it to xlsxwriter's syntax.一般来说,尝试在 excel 中手动重现您想要的 output,然后很容易将其转换为 xlsxwriter 的语法。
Here is a working example:这是一个工作示例:
import pandas as pd
import numpy as np
data = {'Col1': [2, 3, -2, 5],
'Col2': [-5, 6, 7, -8],
'Col3': [np.nan, np.nan, np.nan, np.nan]}
df = pd.DataFrame(data)
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
green = workbook.add_format({'bg_color': '#C6EFCE'})
worksheet.conditional_format('C1:C1048576', {'type': 'formula',
'criteria': '=OR(AND($A1>0,$B1<0),AND($A1<0,$B1>0))',
'format': green})
writer.save()
Output: Output:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.