3

Following problem: each iteration of a for loop a new sheet to an existing excel workbook should be added. in the same iteration a pandas series has to be written into this sheet. At the end there have to be one excel file with multiple sheets each containing one pandas series. I was trying by:

from pandas import Series
for counter in range(n):
   sheet_name = 'Sheet%s' % counter
   series.to_frame(name = '').to_excel('output.xls', sheet_name=sheet_name)

Unfortunately, this code generates a new excel workbook each iteration. As a result, there is only one sheet in there. Please help, I have absolutely no idea.

1 Answer 1

6

According to the documentation, you can pass in an existing ExcelWriter object:

If passing an existing ExcelWriter object, then the sheet will be added to the existing workbook. This can be used to save different DataFrames to one workbook:

>>> writer = pd.ExcelWriter('output.xlsx')
>>> df1.to_excel(writer,'Sheet1')
>>> df2.to_excel(writer,'Sheet2')
>>> writer.save()

So, this should work:

from pandas import Series, ExcelWriter

writer = ExcelWriter('output.xls')
for counter in range(n):
   sheet_name = 'Sheet%s' % counter
   series.to_frame(name = '').to_excel(writer, sheet_name=sheet_name)

writer.save()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.