Search code examples
pythonpandasdataframepython-3.8pandas.excelwriter

Using pandas dataframe style for adjusting column width


I have a dataframe df:

A                               B                  LongColName1     AnotherNa   AnotherName3
Brunner Island is not island    Baltimore is town  0.26             3.88        3.75
Brunner Island is not island    Baltimore is town  -0.59            1.47        2.01

When I dump the above dataframe to excel, it appears as following in excel:

enter image description here

Is there a way to style the dataframe so that dump to excel looks as following:

enter image description here


Solution

  • One approach could be to find the max length of column and set the width of that column explicitly while writing to excel.

    Consider below dataframe:

    In [527]: df                                                                                                                                                                                                
    Out[527]: 
                                     A
    0     Brunner Island is not island
    1  Brunner Island is not an island
    
    len_max = df.A.str.len().max()
    
    from StyleFrame import StyleFrame
    
    excel_writer = StyleFrame.ExcelWriter(filename)
    sf = StyleFrame(df)
    sf.set_column_width(columns=['A'],width=len_max)
    
    sf.to_excel(excel_writer=excel_writer)
    excel_writer.save()