1

I want to write a data frame into excel like this :

    df = DataFrame({'Frequency':lenFreq,'Fatigue Thrust    [N]':meqThrust[iexcel],'Extreme Thrust [N]':extremeThrust[iexcel],'Extreme Thrust DMR [N]':extremeThrustDMR[iexcel],\
                'Fatigue Yaw [Nm]':meqYaw[iexcel],'Extreme Yaw [Nm]':extremeYaw[iexcel],'Extreme Flapwise [Nm]':extremeFlapwise[iexcel][ilenFreq]})

    df.to_excel(workbookOutput, sheet_name='Results', index=False) 

but every time I open the file I need to expand columns :

enter image description here

I would like to know an option to expand columns automatically when writing to excel. Thanks

EdChum
  • 376,765
  • 198
  • 813
  • 562
JPV
  • 1,079
  • 1
  • 18
  • 44
  • 1
    Pandas dev [ruled this out of scope](https://github.com/pydata/pandas/issues/4049). You may find some direction in these answers http://stackoverflow.com/questions/6929115/ – Zero Apr 21 '15 at 15:19
  • Related, if not outright duplicate: http://stackoverflow.com/questions/17326973/is-there-a-way-to-auto-adjust-excel-column-widths-with-pandas-excelwriter (this was even mentioned in the Pandas issue tracker thread linked to by @JohnGalt). – John Y Apr 21 '15 at 16:48

1 Answers1

1

I don't think there is a way to directly re-size excel cells when you call df.to_excel() but here is a way to do it after that call

df = DataFrame({'Frequency':lenFreq,'Fatigue Thrust    [N]':meqThrust[iexcel],'Extreme Thrust [N]':extremeThrust[iexcel],'Extreme Thrust DMR [N]':extremeThrustDMR[iexcel],\
             'Fatigue Yaw [Nm]':meqYaw[iexcel],'Extreme Yaw [Nm]':extremeYaw[iexcel],'Extreme Flapwise [Nm]':extremeFlapwise[iexcel][ilenFreq]})

df.to_excel(workbookOutput, sheet_name='Results', index=False)

sheet = workbookOutput.sheet_by_name('Results')
nrows = len(sheet.get_rows())
ncolumns = len(sheet.get_cols())

for row_index in range (nrows):
    for column_index in range(ncolumns) :
      cwidth = sheet.col(column_index).width
      column_data = sheet.cell(row_index,column_index).value
      if (len(column_data)*367) > cwidth:  
          sheet.col(column_index).width = (len(column_data)*367) 
farhawa
  • 10,120
  • 16
  • 49
  • 91