Xlsxwriter条件格式问题

Xlsxwriter conditional formatting problem

我有如下所示的条件格式:

worksheet_budget.conditional_format('D2:D100', {'type': 'cell',
                                            'criteria': 'between',
                                            'minimum': 0,
                                            'maximum': 100,
                                            'format': caution})

worksheet_budget.conditional_format('D2:D100', {'type': 'cell',
                                           'criteria': '<',
                                           'value': 0,
                                           'format': over})

它的目的是针对每个小于 0 的值,将格式切换为超过 0 - 100 之间的警告格式。然而,最终发生的是对于没有值的字段,它会将其视为 0 并使用警告格式。我只希望具有会计编号的字段具有两种格式之一。如果它是空的,它应该没有格式。

正如@martineau 指出的那样,并且如 the documentation 中突出显示的那样,将第二种格式的 'type': 'cell' 更改为 'type': 'blanks' 应该将 over 格式应用于所有单元格没有价值。

您还需要删除 criteriavalue 键:

worksheet_budget.conditional_format('D2:D100', {'type': 'blanks',
                                       'format': over})

几乎每次我在 XlsxWriter 中回答有关条件格式的问题时,我都会说同样的话:首先弄清楚如何在 Excel 中进行操作,然后将其应用于 XlsxWriter。

看来 Excel 中 issue/feature 已经知道将空白单元格视为零的条件格式问题。我遵循了 this post 中关于该问题的一种方法的建议,并为空白单元格设置了额外的默认格式。我还需要设置 stop_if_true 属性。这是一个工作示例:

import xlsxwriter

workbook = xlsxwriter.Workbook('conditional_format.xlsx')
worksheet = workbook.add_worksheet()

# Add a format. Light red fill with dark red text.
format1 = workbook.add_format({'bg_color': '#FFC7CE',
                               'font_color': '#9C0006'})

# Add a format. Green fill with dark green text.
format2 = workbook.add_format({'bg_color': '#C6EFCE',
                               'font_color': '#006100'})

# Add a default format.
format3 = workbook.add_format()


# Some sample data to run the conditional formatting against.
data = [
    [34, -75, None, 75, 66, 84, 86],
    [6, 24, 1, 60, 3, 26, 59],
    [None, 79, 97, -13, 22, 5, 14],
    [-27, -71, None, 17, 18, 0, 47],
    [88, 25, -33, 23, 67, "", 36],
    ['', 100, 20, 88, 54, 54, 88],
    [6, 57, '', 28, 10, 41, 48],
    [52, 78, -1, 96, 26, 0, ""],
    [60, -54, 81, None, 81, 90, 55],
    [70, 5, 46, 14, 71, 41, 21],
]


for row, row_data in enumerate(data):
    worksheet.write_row(row + 2, 1, row_data)

worksheet.conditional_format('B3:H12', {'type': 'blanks',
                                        'stop_if_true': True,
                                        'format': format3})

worksheet.conditional_format('B3:H12', {'type': 'cell',
                                        'criteria': 'between',
                                        'minimum': 0,
                                        'maximum': 100,
                                        'format': format1})

worksheet.conditional_format('B3:H12', {'type': 'cell',
                                        'criteria': '<',
                                        'value': 0,
                                        'format': format2})

workbook.close()

输出: