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()
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments