问题
Wrap text does not work for me. I tried the below code:
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 )
Here is the screenshot of my result
Wrap text does not work for me. I tried the below code:
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 )
Here is the screenshot of my result
Got the below error using @amanb's solution/code
My dataframe looks something like below
回答1:
According to the official documentation for Formatting of the Dataframe headers:
Pandas writes the dataframe header with a default cell format. Since it is a cell format it cannot be overridden using set_row(). If you wish to use your own format for the headings then the best approach is to turn off the automatic header from Pandas and write your own.
So, we turn off the automatic header from Pandas and write our own. The defined header_format
should be applied to each column header in the df_input
and written to the worksheet. The following is customized to your requirement and a similar example is shown in the official docs.
# 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)
来源:https://stackoverflow.com/questions/55183760/text-wrap-format-gets-ignored-using-worksheet-formatting