How do I correctly auto fit an excel file column with a function

106 Views Asked by At

I am trying to autofit my excel ws columns with the following function:

def autoFit(ExcelWriter,SheetName,DF):
    for column in DF:
        print(column)
        column_length = max(DF[column].astype(str).map(len).max(), len(column))
        col_idx = DF.columns.get_loc(column)
        ExcelWriter.sheets[SheetName].set_column(col_idx, col_idx, column_length)
    return 1

and then I call it like below :

writer = pd.ExcelWriter("Blabla.xlsx", engine = 'xlsxwriter')    
autoFit(writer,'TEST',MYDF)
writer.save()

but when I open excel file, the columns are not fitted, what am I doing wrong there ?

0

There are 0 best solutions below