JPV
JPV

Reputation: 1079

Write data frame into excel with wide column

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

Upvotes: 1

Views: 419

Answers (1)

farhawa
farhawa

Reputation: 10407

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) 

Upvotes: 1

Related Questions