xlswriter格式化范围

Gab*_*iel 8 python pandas xlsxwriter

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

例如:

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

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

range2 = "B2:C15"
worksheet2.write(range2, perc_fmt)
Run Code Online (Sandbox Code Playgroud)

它说:

TypeError: Unsupported type <class 'xlsxwriter.format.Format'> in write()
Run Code Online (Sandbox Code Playgroud)

Gab*_*iel 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})  
Run Code Online (Sandbox Code Playgroud)