在下面的代码中,我将数字格式应用于我的Excel工作表中的每一列。但是,我似乎无法想象将多个格式应用于特定列,无论是居中还是编号最终都被覆盖了。是否可以将两种类型的格式应用于一列?
def to_excel(video_report):
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
video_report.to_excel(writer, sheet_name='Sheet1', na_rep="-")
# Get the xlsxwriter objects from the dataframe writer object.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Add some cell formats.
integer = workbook.add_format({'num_format': '0'})
decimal = workbook.add_format({'num_format': '0.00'})
percentage = workbook.add_format({'num_format': '0.0%'})
center = workbook.add_format({'align': 'center'})
# APPLY CENTERING
worksheet.set_column('B:L', None, center)
# APPLY NUMBER FORMATTING
worksheet.set_column('B:B', 13, integer )
worksheet.set_column('C:C', 17, percentage )
worksheet.set_column('D:D', 19, percentage )
worksheet.set_column('E:E', 15, integer )
worksheet.set_column('F:F', 15, percentage )
worksheet.set_column('G:G', 15, decimal )
worksheet.set_column('H:H', 13, integer )
worksheet.set_column('I:I', 13, integer )
worksheet.set_column('J:J', 13, integer )
worksheet.set_column('K:K', 13, integer )
worksheet.set_column('L:L', 13, integer )
writer.save()
to_excel(video_report)
答案 0 :(得分:4)
是否可以将两种类型的格式应用于一列?
是。通过将两个或多个属性添加到您正在使用的格式对象。例如:
integer = workbook.add_format({'num_format': '0', 'align': 'center'})
请参阅XlsxWriter docs on how to use formats。
答案 1 :(得分:3)
虽然jmcnamara最能回答这个问题,但您也可以定义一个新的格式对象。替代示例:
header = workbook.add_format({'align': 'center'})
header.set_bold()
header.set_italic()
header.set_underline()
worksheet.write(0, col_hdr, key, header)