簡體   English   中英

基於公式的 xlsxwriter 條件格式不起作用

[英]xlsxwriter Conditional Format based on Formula not working

如果 A 列中的值以特定單詞開頭,我想格式化整行。

此代碼檢查單元格 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})

然而,這是我修改后的代碼,用於檢查單元格值是否等於“總計”或以“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 )但為什么第二個公式有問題。

該公式在條件格式中無效。 您會在 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()

輸出:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM