How to Auto-Adjust Excel Column Widths With Pandas.ExcelWriter

  • Home /
  • Blog Posts /
  • How to Auto-Adjust Excel column widths with pandas.ExcelWriter

You have successfully written your pandas Dataframe to an Excel file, but when you open it, all the columns are squashed up against each other.

There is an easy fix to auto-adjusting your column widths.

Auto Adjusting Column Widths in Pandas

writer = pd.ExcelWriter('file.xlsx') 
df.to_excel(writer, sheet_name='sheetName', index=False, na_rep='NaN')

for column in df:
    column_length = max(df[column].astype(str).map(len).max(), len(column))
    col_idx = df.columns.get_loc(column)
    writer.sheets['sheetName'].set_column(col_idx, col_idx, column_length)

writer.save()