Home » excel » python – Pandas: Exporting multiple DataFrames to multiple xlsx files

python – Pandas: Exporting multiple DataFrames to multiple xlsx files

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have multiple DataFrames (DF), such as

  • df1
  • df2
  • df24

and I would like to export each DF to a separate xlsx file, such as

  • ‘output_T1.xlsx’ for df1,
  • ‘output_T2.xlsx’ for df2
  • ‘output_T24.xlsx’ for df24.

Although I know how to do it with to_csv:

df[i].to_csv('output_T%s.csv' %(1+i), index = False) 

I cannot find out how to do it with the df.to_excel.
Here is my code what I made and I receive a type error.

for i in xrange(n):
    writer[i] = pd.ExcelWriter('output_P%s.xlsx')
    dfLP[i].to_excel(writer[i], sheet_name='Sheet1')
    writer.save()
    %(1+i)

TypeError: ‘_XlsxWriter’ object does not support item assignment

Any hint, suggestion would be appreciated.

Cheers,

How to&Answers:

The problem is here:

writer[i] = pd.ExcelWriter('output_P%s.xlsx')

You say writer is an ExcelWriter. So why do you try to assign to its [i]th element? Try this:

for i in xrange(n):
    filename = 'output_P%s.xlsx' % (1+i)
    dfLP[i].to_excel(filename, sheet_name='Sheet1')