To dynamically adjust all the column lengths,
writer = pd.ExcelWriter('temp.xlsx')
df.to_excel(writer, sheet_name='sheetName', index=False)
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.close()
To manually adjust a column using column name,
col_idx = df.columns.get_loc('columnName')
writer.sheets['sheetName'].set_column(col_idx, col_idx, 20)
To manually adjust a column using column index,
writer.sheets['sheetName'].set_column(col_idx, col_idx, 20)
Potential error messages:
AttributeError: 'Worksheet' object has no attribute 'set_column'
--> install "xlsxwriter" module
--> use the installed as the engine, writer = pd.ExcelWriter('temp.xlsx', engine='xlsxwriter')