Writing multiple pandas dataframes to multiple excel worksheets

Milhouse picture Milhouse · Feb 29, 2016 · Viewed 7.7k times · Source

I'd like for the code to run 12345 thru the loop, input it in a worksheet, then start on 54321 and do the same thing except input the dataframe into a new worksheet but in the same workbook. Below is my code.

workbook = xlsxwriter.Workbook('Renewals.xlsx')

groups = ['12345', '54321']

for x in groups:

    (Do a bunch of data manipulation and get pandas df called renewals)

    writer = pd.ExcelWriter('Renewals.xlsx', engine='xlsxwriter')
    worksheet = workbook.add_worksheet(str(x))
    renewals.to_excel(writer, sheet_name=str(x)) 

When this runs, I am left with a workbook with only 1 worksheet (54321).

Answer

Sam picture Sam · Feb 29, 2016

try something like this:

import pandas as pd
#initialze the excel writer
writer = pd.ExcelWriter('MyFile.xlsx', engine='xlsxwriter')

#store your dataframes in a  dict, where the key is the sheet name you want
frames = {'sheetName_1': dataframe1, 'sheetName_2': dataframe2,
        'sheetName_3': dataframe3}

#now loop thru and put each on a specific sheet
for sheet, frame in  frames.iteritems(): # .use .items for python 3.X
    frame.to_excel(writer, sheet_name = sheet)

#critical last step
writer.save()