Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save list of DataFrames to multisheet Excel spreadsheet

How can I export a list of DataFrames into one Excel spreadsheet?
The docs for to_excel state:

Notes
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 = ExcelWriter('output.xlsx')
df1.to_excel(writer, 'sheet1')
df2.to_excel(writer, 'sheet2')
writer.save()

Following this, I thought I could write a function which saves a list of DataFrames to one spreadsheet as follows:

from openpyxl.writer.excel import ExcelWriter def save_xls(list_dfs, xls_path):     writer = ExcelWriter(xls_path)     for n, df in enumerate(list_dfs):         df.to_excel(writer,'sheet%s' % n)     writer.save() 

However (with a list of two small DataFrames, each of which can save to_excel individually), an exception is raised (Edit: traceback removed):

AttributeError: 'str' object has no attribute 'worksheets' 

Presumably I am not calling ExcelWriter correctly, how should I be in order to do this?

like image 946
Andy Hayden Avatar asked Jan 08 '13 23:01

Andy Hayden


People also ask

How do I write pandas Dataframes to an existing Excel spreadsheet?

You can write any data (lists, strings, numbers etc) to Excel, by first converting it into a Pandas DataFrame and then writing the DataFrame to Excel. To export a Pandas DataFrame as an Excel file (extension: . xlsx, . xls), use the to_excel() method.


Video Answer


1 Answers

You should be using pandas own ExcelWriter class:

from pandas import ExcelWriter # from pandas.io.parsers import ExcelWriter 

Then the save_xls function works as expected:

def save_xls(list_dfs, xls_path):     with ExcelWriter(xls_path) as writer:         for n, df in enumerate(list_dfs):             df.to_excel(writer,'sheet%s' % n)         writer.save() 
like image 73
Andy Hayden Avatar answered Oct 22 '22 08:10

Andy Hayden