【发布时间】:2021-06-14 08:28:09
【问题描述】:
我正在尝试将 pandas DataFrame 写入多个 Excel 工作表,工作表名称由“服务类型”列确定。
在我的函数中,我正在尝试编写一些代码来查看 Excel 工作表中的每一列自动调整宽度,以便每行中的所有文本都可见。
我认为到目前为止我所写的内容可以工作,但我不确定如何正确识别sheet_name,因为我正在查看a str(index)。
这是我目前写的:
# Create a final DataFrame called "final_df" where rows have an Error value of 1
final_df = stacked_df[stacked_df.Error == 1]
# Creates a Pandas Excel writer using XlsxWriter as the engine
writer = pd.ExcelWriter(LOGNAME, engine='xlsxwriter')
# Group the output by "Service type" and save each DataFrame to a seperate sheet
for index, group_df in final_df.groupby("Service type"):
group_df.to_excel(writer, sheet_name=str(index), index=False)
# Auto-adjust column's width
for column in stacked_df:
column_width = max(stacked_df[column].astype(str).map(len).max(), len(column))
col_idx = stacked_df.columns.get_loc(column)
writer.sheets[sheet_name=str(index)].set_column(col_idx, col_idx, column_width)
# Close the Pandas Excel writer and output the Excel file
writer.save()
我该如何进行这项工作?谢谢。
【问题讨论】:
-
看wrapping text in excel,需要用到xlsxwriter,看documentation here