0

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

Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
Zanam
  • 4,607
  • 13
  • 67
  • 143

2 Answers2

4

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()
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
  • A styled Dataframe doesn't have a method called "set_column_width". To my opinion this answer is not correct. this line will not work "sf.set_column_width(columns=['A'],width=len_max)" – floupinette Mar 16 '23 at 17:52
  • It was there at the time when this question was asked. Has it been removed from latest pandas version? – Mayank Porwal Mar 18 '23 at 08:21
1

There is no way to auto adjust column width. But there are some workarounds mentioned in this post Is there a way to auto-adjust Excel column widths with pandas.ExcelWriter?

NYC Coder
  • 7,424
  • 2
  • 11
  • 24