使用条件格式填充颜色

时间:2019-03-13 15:53:51

标签: python excel

我有一个熊猫数据框,如下所示:

import io

df = pd.read_table(io.StringIO('''\
A       B              C          
SDF     899501607.2   -26152567.7
ISB     464284188.7   -20278910.23

我想使用pd.ExcelWriter将黄色填充到标题A,将红色填充到标题B,将蓝色填充到标题C。 我在下面的代码中尝试为列A填充黄色,但它用黄色填充了标题的值,而不仅仅是标题(单元格A1)

writer = pd.ExcelWriter("output_file_name.xlsx", engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook  = writer.book
worksheet = writer.sheets['Sheet1']
yellow_format = workbook.add_format({'bg_color':'yellow'})
l = ['A1:A1']
for columns in l:
    worksheet.set_column(columns, 25, yellow_format)

1 个答案:

答案 0 :(得分:0)

xlsxwriter用于创建Excel文件,但无法读取它们。写入后,它也不能格式化 specific 单元格。

但是您可以使用这两种方法之一来仅格式化标题。

使用conditional_format(最快):

yellow_format = workbook.add_format({'bg_color': 'yellow'})
red_format = workbook.add_format({'bg_color': 'red'})
blue_format = workbook.add_format({'bg_color': 'blue'})

worksheet.conditional_format("A1", {'type': 'no_blanks', 'format': yellow_format})
worksheet.conditional_format("B1", {'type': 'no_blanks', 'format': red_format})
worksheet.conditional_format("C1", {'type': 'no_blanks', 'format': blue_format})

使用set_columnset_row的组合(如果要为每行设置白色,则比较慢):

yellow_format = workbook.add_format({'bg_color': 'yellow'})
red_format = workbook.add_format({'bg_color': 'red'})
blue_format = workbook.add_format({'bg_color': 'blue'})
white_format = workbook.add_format({'bg_color': 'white'})

worksheet.set_column(first_col=0, last_col=0, cell_format=yellow_format)
worksheet.set_column(first_col=1, last_col=1, cell_format=red_format)
worksheet.set_column(first_col=2, last_col=2, cell_format=blue_format)

for i in range(1, 1048576):
    worksheet.set_row(row=i, cell_format=white_format)