python 基于公式的xlsxwriter条件格式无效

wlp8pajw  于 2022-12-17  发布在  Python
关注(0)|答案(1)|浏览(180)

如果A列中的值以特定的单词开头,我想设置整行的格式。
此代码检查单元格A#是否等于“Totals”,并设置整行的格式:

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})

但是,下面是我修改的代码,用于检查单元格值是否等于“Totals”或以“A1”、“A2”或“A3”开头。当我尝试打开文件时,返回错误:

worksheet.conditional_format(0,0,10, 10, {"type": "formula","criteria": '=OR(COUNTIF(INDIRECT("A"&ROW()),{"Totals","A1*","A2*","A3*"}))',"format": testformat})

我在Excel中测试了公式,它们工作正常(返回TRUE),但为什么第二个公式会有问题呢?

5n0oy7gb

5n0oy7gb1#

该公式在条件格式中无效。您将在Excel中收到如下警告:

警告:不能将引用运算符(如联合、交集和范围)、数组常量或LAMBDA函数用于条件格式设置条件。

可能有几种方法可以得到你想要的条件格式,但我只想把它分成几个重叠的简单条件格式。

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()

输出:

相关问题