[英]xlsxwriter Conditional Format based on Formula not working
I want to format an entire row if the value in column A starts with specific words.如果 A 列中的值以特定单词开头,我想格式化整行。
This code checks if cell A# equals 'Totals' and formats the entire row:此代码检查单元格 A# 是否等于“总计”并设置整行的格式:
testformat = wb.add_format({'bg_color': '#D9D9D9', 'font_color': 'red'})
worksheet.conditional_format(0,0,10, 10, {"type": "formula","criteria": '=INDIRECT("A"&ROW())="Totals"',"format": testformat})
However here is my modified code to check if the cell value equals 'Totals' or starts with 'A1', 'A2', or 'A3'.然而,这是我修改后的代码,用于检查单元格值是否等于“总计”或以“A1”、“A2”或“A3”开头。 returns an error when I try to open the file:当我尝试打开文件时返回错误:
worksheet.conditional_format(0,0,10, 10, {"type": "formula","criteria": '=OR(COUNTIF(INDIRECT("A"&ROW()),{"Totals","A1*","A2*","A3*"}))',"format": testformat})
I tested the formulas in Excel and they work fine (returning TRUE
) but why is there a problem with the second formula.我在 Excel 中测试了公式,它们工作正常(返回TRUE
)但为什么第二个公式有问题。
That formula isn't valid in an conditional format.该公式在条件格式中无效。 Your would get a warning like this in Excel:您会在 Excel 中收到这样的警告:
Alert : You may not use reference operators (such as unions, intersections, and ranges), array constants, or the LAMBDA function for Conditional Formatting criteria.警告:您不能将引用运算符(例如并集、交集和范围)、数组常量或 LAMBDA 函数用于条件格式设置条件。
There are probably several ways to get the conditional format you want but I would just break it into several overlapping simple conditional formats.可能有几种方法可以获得您想要的条件格式,但我只是将其分解为几个重叠的简单条件格式。 Something like this:像这样:
import xlsxwriter
workbook = xlsxwriter.Workbook('conditional_format.xlsx')
worksheet = workbook.add_worksheet()
# Add a format. Green fill with dark green text.
format1 = workbook.add_format({'bg_color': '#C6EFCE',
'font_color': '#006100'})
# Some sample data.
data = [
["Total", 72, 38, 30, 75, 48, 75, 66, 84, 86],
["A1", 24, 1, 84, 54, 62, 60, 3, 26, 59],
["B1", 79, 97, 13, 85, 93, 93, 22, 5, 14],
["A2", 71, 40, 17, 18, 79, 90, 93, 29, 47],
["Total", 25, 33, 23, 67, 1, 59, 79, 47, 36],
["A13", 99, 20, 88, 29, 33, 38, 54, 54, 88],
["B1", 57, 88, 28, 10, 26, 37, 7, 41, 48],
["A31", 78, 1, 96, 26, 45, 47, 33, 96, 36],
["B1", 54, 81, 66, 81, 90, 80, 93, 12, 55],
["A21", 5, 46, 14, 71, 19, 66, 36, 41, 21],
]
# Write the sample data.
for row, row_data in enumerate(data):
worksheet.write_row(row , 0, row_data)
# Add conditional formats to highlight rows.
worksheet.conditional_format(0, 0, 9, 9,
{'type': 'formula',
'criteria': '=$A1 = "Total"',
'format': format1})
# Repeat this one for the A* variants.
worksheet.conditional_format(0, 0, 9, 9,
{'type': 'formula',
'criteria': '=LEFT($A1,2)="A1"',
'format': format1})
workbook.close()
Output:输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.