xlswriter格式化范围

时间:2015-12-01 17:27:14

标签: python pandas xlsxwriter

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

4 个答案:

答案 0 :(得分:9)

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

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

答案 1 :(得分:1)

  

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

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

答案 2 :(得分:0)

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

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

我最初尝试过 'criteria' : '<>', 'value' : 0 但这并没有捕捉到空白单元格。如果您使用 < 99999999999 它会将文本字段编码为 False 并且不会对其进行编码。

答案 3 :(得分:0)

你可以使用:

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

这将为您节省一行代码