Sha*_*noo 1 excel python-3.x xlsxwriter
换行文字对我不起作用。我尝试了以下代码:
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 )
Run Code Online (Sandbox Code Playgroud)
这是我的结果截图
换行文字对我不起作用。我尝试了以下代码:
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 )
Run Code Online (Sandbox Code Playgroud)
这是我的结果截图
我的数据框看起来像下面
根据Dataframe 标头格式化的官方文档:
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)
Run Code Online (Sandbox Code Playgroud)