Thursday, February 29, 2024
HomeSoftware EngineeringEasy methods to Auto-Regulate Excel column widths with pandas.ExcelWriter

Easy methods to Auto-Regulate Excel column widths with pandas.ExcelWriter


You may have efficiently written your pandas Dataframe to an Excel file, however whenever you open it, all of the columns are squashed up in opposition to one another.

There may be a simple repair to auto-adjusting your column widths.

Auto Adjusting Column Widths in Pandas

author = pd.ExcelWriter('file.xlsx') 
df.to_excel(author, 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)
    author.sheets['sheetName'].set_column(col_idx, col_idx, column_length)

author.save()
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments