xlsxwriter 格式化范围

xlswriter formatting a range

在 xlswriter 中,一旦定义了格式,如何将其应用于范围而不是整列或整行?

例如:

perc_fmt = workbook.add_format({'num_format': '0.00%','align': 'center'})
worksheet.set_column('B:B', 10.00, perc_fmt)

这会应用于整个 "B" 列,但是 "perc_fmt" 如何应用于一个范围,例如,如果我这样做:

range2 = "B2:C15"
worksheet2.write(range2, perc_fmt)

它说:

TypeError: Unsupported type <class 'xlsxwriter.format.Format'> in write()

In xlswriter, once a format is defined, how can you apply it to a range and not to the whole column or the whole row?

没有辅助函数可以执行此操作。您需要遍历范围并将数据和格式应用于每个单元格。

实际上我找到了一个避免循环的解决方法。 您只需要使用条件格式(将范围作为输入)并只格式化所有案例。例如:

worksheet2.conditional_format(color_range2, {'type': 'cell',
                                     'criteria': '>=',
                                     'value': 0, 'format': perc_fmt})
worksheet2.conditional_format(color_range2, {'type': 'cell',
                                     'criteria': '<',
                                     'value': 0, 'format': perc_fmt})  

我花了很长时间才找到这个答案,谢谢。当您的范围包括空白和文本字段时,我会提供仅包含一个块的附加解决方案。这会将范围 A2:N5 转换为我之前在代码中定义的桃色格式。当然,如果您的数据集中确实有大量负数,则必须使数字更负。

    worksheet.conditional_format('A2:N5', {'type': 'cell',
                                           'criteria' : '>', 
                                           'value' : -99999999999,
                                           'format' : peach_format})

我最初尝试 'criteria' : '<>', 'value' : 0 但没有捕获空白单元格。如果您使用 < 99999999999,它会将文本字段编码为 False 而不会编码它们。

您可以使用:

{
    'type': 'cell',
    'criteria': 'between',
    'minimum': -10000,
    'maximum': 10000,
    'format': perc_fmt
}

这将为您节省一行代码