【问题标题】:Python - How to set or autofit the column width in an Excel sheet?Python - 如何在 Excel 工作表中设置或自动调整列宽?
【发布时间】: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()

这是 Excel 工作表的样子:

这就是我想要的样子:

我该如何进行这项工作?谢谢。

【问题讨论】:

标签: python excel


【解决方案1】:

writer.sheets 的类型是dict,其中键是工作表的名称,值是工作表对象,因此您尝试引用工作表的方式不正确。

writer.sheets[sheet_name=str(index)] 不正确

writer.sheets[sheet_name_as_string] 正确

除此之外,逻辑似乎存在问题:您尝试在第二个循环中使用的 index 变量未定义。如果您尝试使用第一个for 循环中的index,那么您应该嵌套循环

例如:

writer = pd.ExcelWriter(LOGNAME, engine="xlsxwriter")

for sheet_idx, group_df in data.groupby("Service type"):
    
    # Create a worksheet from current GROUPBY object
    group_df.to_excel(writer, sheet_name=str(sheet_idx), index=False)

    # Loop through columns of current worksheet,
    # and set correct width for each one
    for column in group_df:
        column_width = max(group_df[column].astype(str).map(len).max(), len(column))
        col_idx = group_df.columns.get_loc(column)
        writer.sheets[str(sheet_idx)].set_column(col_idx, col_idx, column_width)

writer.save()

【讨论】:

    猜你喜欢
    • 2015-10-31
    • 2016-01-21
    • 1970-01-01
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 2015-04-16
    • 2015-07-13
    • 1970-01-01
    相关资源
    最近更新 更多