question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Allow ExcelWriter() to add sheets to existing workbook

See original GitHub issue

The ability of ExcelWriter to save different dataframes to different worksheets is great for sharing those dfs with the python-deficient. But this quickly leads to a need to add worksheets to an existing workbook, not just creating one from scratch; something like:

df0=pd.DataFrame(np.arange(3))
df0.to_excel('foo.xlsx','Data 0')

df1=pd.DataFrame(np.arange(2))
df1.to_excel('foo.xlsx','Data 1')

The following little diff to io/parsers.py implements this behavior for *.xlsx files:

diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 89f892d..7f010ee 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -2099,12 +2099,19 @@ class ExcelWriter(object):
             self.fm_date = xlwt.easyxf(num_format_str='YYYY-MM-DD')
         else:
             from openpyxl.workbook import Workbook
-            self.book = Workbook()  # optimized_write=True)
-            # open pyxl 1.6.1 adds a dummy sheet remove it
-            if self.book.worksheets:
-                self.book.remove_sheet(self.book.worksheets[0])
+            from openpyxl.reader.excel import load_workbook
+
+            try:
+               self.book=load_workbook(filename = path)
+               self.sheets={wks.title:wks for wks in self.book.worksheets}
+            except InvalidFileException:
+                self.book = Workbook()  # optimized_write=True)
+                # open pyxl 1.6.1 adds a dummy sheet remove it
+                if self.book.worksheets:
+                    self.book.remove_sheet(self.book.worksheets[0])
+                self.sheets = {}
+
         self.path = path
-        self.sheets = {}
         self.cur_sheet = None

Doing this for *.xls files is a little harder.

Issue Analytics

  • State:closed
  • Created 10 years ago
  • Reactions:3
  • Comments:41 (16 by maintainers)

github_iconTop GitHub Comments

19reactions
ankostiscommented, Dec 18, 2015

This stackoverflow workaround, which is based in openpyxl, may work (EDIT: indeed works, checked with pandas-0.17.0):

import pandas
from openpyxl import load_workbook

book = load_workbook('Masterfile.xlsx')
writer = pandas.ExcelWriter('Masterfile.xlsx', engine='openpyxl') 
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])

writer.save()
12reactions
jtratnercommented, Sep 22, 2013

Because of how to_excel is set up, this would mean reading in and then writing the file each time (because to_excel with a path argument saves the file). The right way to do this is to use ExcelWriter:

import pandas as pd
writer = pd.ExcelWriter('foo.xlsx')
df.to_excel(writer, 'Data 0')
df.to_excel(writer, 'Data 1')
writer.save()

I could see (eventually) adding an option to ExcelWriter that doesn’t overwrite the file. But, yet again, that may mean writing in the entire file first. I don’t know.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to save a new sheet in an existing excel file, using Pandas?
For creating a new file ... add df = pd.DataFrame(data) #Load existing sheet as it is book ... book df1.to_excel(writer,sheet_name = 'Sheet3') writer.save()...
Read more >
How to add new worksheets to Excel workbooks with Pandas
In this article I am looking to explain how to add a new worksheet to an already existing Excel workbook, using the famous...
Read more >
Add new sheet to excel using pandas - Thinking Neuron
A data frame can be added as a new sheet to an existing excel sheet. For this operation, the library required is openpyxl....
Read more >
Working with Python Pandas and XlsxWriter - Read the Docs
To use XlsxWriter with Pandas you specify it as the Excel writer engine: ... objects. workbook = writer.book worksheet = writer.sheets['Sheet1'] # Add...
Read more >
Export Pandas DataFrames to new & existing Excel workbook
In this tutorial, I'll show you how to export a Pandas dataframe to a new Excel workbook, or to an existing Excel workbook....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found