如何在Excel工作表中自动调整列宽?

2024-06-10 20:58:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些代码将数据框写入多个Excel工作表,工作表名称由“服务类型”列中的字符决定

在我的函数中,我试图编写一些代码,查看Excel工作表中的每一列,自动调整宽度,使每一行中的所有文本都可见

我认为到目前为止我所写的东西可以工作,但是我不确定如何正确地识别sheet_name,因为我在看一个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()

这是Excel工作表的外观: enter image description here

这就是我希望它看起来的样子: enter image description here

关于如何使代码正常工作,有什么建议吗?谢谢