set_column没有将颜色格式应用于大型excel文件的列

时间:2019-04-09 13:38:48

标签: python python-3.x

我正在尝试突出显示使用不同字体颜色的列,以便于用户通知,但这没有发生。尝试了各种尝试,但不确定是什么问题。除了其他尝试之外,我还尝试评论其他工作表

with pd.ExcelWriter("C:\myDocs\Python\MAY_CCPS_CCSO_Preload_Validated.xlsx", engine='xlsxwriter') as writer:
     CCSO_Preload_Sheet1.to_excel(writer, index = False, sheet_name='SO_1Header')
#     CCSO_Preload_Sheet2.to_excel(writer, index = False, sheet_name="SO_2Item",engine='xlsxwriter')
#     CCSO_Preload_Sheet3.to_excel(writer, index = False, sheet_name="SO_3_Schedules",engine='xlsxwriter')
#     CCSO_Preload_Sheet4.to_excel(writer, index = False, sheet_name="SO_4Partners",engine='xlsxwriter')
#     CCSO_Preload_Sheet5.to_excel(writer, index = False, sheet_name="SO_5Long_Text",engine='xlsxwriter')
workbook  = writer.book
worksheet = writer.sheets['SO_1Header']
format1 = workbook.add_format({'bold': True, 'font_color': 'red', 'bg_color': 'yellow'})
worksheet.set_column('B:B', 40, format1)
writer.save()

1 个答案:

答案 0 :(得分:0)

问题似乎是您使用的是with上下文管理器,但是格式代码不在该块中。因此,当您尝试格式化文件时,该文件已经关闭。

更改缩进程序可以按预期工作:

import pandas as pd

data = [10, 20, 30, 40, 50, 60]

CCSO_Preload_Sheet1 = pd.DataFrame({'Heading1': data,
                                    'Heading2': data})

with pd.ExcelWriter("test.xlsx", engine='xlsxwriter') as writer:
    CCSO_Preload_Sheet1.to_excel(writer, 
                                  index = False, 
                                  sheet_name='SO_1Header')

    workbook  = writer.book
    worksheet = writer.sheets['SO_1Header']

    format1 = workbook.add_format({'bold': True, 
                                   'font_color': 'red', 
                                   'bg_color': 'yellow'})

    worksheet.set_column('B:B', 40, format1)

输出:

enter image description here