Home » excel » python – multiple dataframes per sheet, multiple sheets per workbook

python – multiple dataframes per sheet, multiple sheets per workbook

Posted by: admin May 14, 2020 Leave a comment

Questions:

I wrote a function so that I can write multiple dataframes onto a single excel sheet, then have multiple sheets within one excel workbook. I am able to achieve the first part, but not the second. When the script runs, it overwrites the existing tab and writes over it with the new one, meaning that every time I open the output file, it only has one sheet, the latest one.

I’ve always been a little puzzled by the writer.save() function and when to use it (i.e.: in or our of a loop). Any suggestions?

def dfs_to_sheet(dflist, bookname, sheetname, startrow = 0):
    writer = pd.ExcelWriter('{}.xlsx'.format(bookname), engine='openpyxl')
    numdfs = 0
    startrow = 0
    for i in dflist:
        if numdfs == 0:
            i.to_excel(writer, sheet_name=sheetname,  startrow = startrow)
        elif numdfs != 0:
            i.to_excel(writer, sheet_name = sheetname, startrow = startrow)
        startrow = startrow + len(i) + 2
        numdfs += 1
    writer.save()
How to&Answers:

The answer you are looking for is related to the solution here, but since you want to call this over multiple iterations, it’s a little more complicated. My solution is below, but keep in mind, this gets messy if there are duplicate sheets (e.g., if Sheet1 exists, and you try to add Sheet1 again, it becomes Sheet11).

import pandas as pd
import os.path
from openpyxl import load_workbook

def dfs_to_sheet(dflist, bookname, sheetname, startrow = 0):
    book_file = '{}.xlsx'.format(bookname)
    writer = pd.ExcelWriter(book_file, engine='openpyxl')
    if os.path.isfile(book_file):
        writer.book = load_workbook(book_file)
    numdfs = 0
    startrow = 0
    for i in dflist:
        if numdfs == 0:
            i.to_excel(writer, sheet_name = sheetname,  startrow = startrow)
        elif numdfs != 0:
            i.to_excel(writer, sheet_name = sheetname, startrow = startrow)
        startrow = startrow + len(i) + 2
        numdfs += 1
    writer.save()
    writer.close()

Answer:

This is how I do it. New sheet should be added to a Excel workbook, and the workbook object also should get the new sheet.

writer = pd.ExcelWriter('example.xlsx', engine='xlsxwriter')
wb = writer.book
sh = wb.add_worksheet('Sheet1')
writer.sheets['Sheet1'] = sh
sh2 = wb.add_worksheet('Sheet2')
writer.sheets['Sheet2'] = sh2
........
sh.white(...