换行文本对我不起作用。我尝试了下面的代码:
writer = pd.ExcelWriter(out_file_name, engine='xlsxwriter')
df_input.to_excel(writer, sheet_name='Inputs')
workbook = writer.book
worksheet_input = writer.sheets['Inputs']
header_format = workbook.add_format({
'bold': True,
'text_wrap': True})
# Write the column headers with the defined format.
worksheet_input.set_row(1,45,header_format )
这是我的结果的屏幕截图
换行文本对我不起作用。我尝试了下面的代码:
writer = pd.ExcelWriter(out_file_name, engine='xlsxwriter')
df_input.to_excel(writer, sheet_name='Inputs')
workbook = writer.book
worksheet_input = writer.sheets['Inputs']
header_format = workbook.add_format({
'bold': True,
'text_wrap': True})
# Write the column headers with the defined format.
worksheet_input.set_row(1,45,header_format )
这是我的结果的屏幕截图
我的数据框如下所示
根据Formatting of the Dataframe headers的官方文件:
Pandas使用默认单元格格式写入数据帧标头。由于它是一种单元格格式,因此无法使用set_row()覆盖它。如果您希望使用自己的格式作为标题,那么最好的方法是关闭Pandas的自动标题并编写自己的标题。
所以,我们关闭Pandas的自动标题并编写我们自己的标题。定义的header_format
应该应用于df_input
中的每个列标题并写入工作表。以下是根据您的要求定制的,官方文档中显示了类似的示例。
# Turn off the default header and skip one row to allow us to insert a
# user defined header.
df_input.to_excel(writer, sheet_name='Inputs', startrow=1, header=False)
# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Inputs']
# Add a header format.
header_format = workbook.add_format({
'bold': True,
'text_wrap': True})
# Write the column headers with the defined format.
for col_num, value in enumerate(df_input.columns.values):
worksheet.write(0, col_num + 1, value, header_format)