pandas: Writing to an existing excel file (xlsx) using to_excel

Viewed 8459

I have a simple use case for df.to_excel() that I'm struggling with. I want to write to a specific worksheet tab (let's call it "Data") of an existing XLSX workbook, which could be referenced by formulas and pivots on other tabs.

I've tried to modify ExcelWriter in two ways but both produce errors from openpyxl.

  1. Read an existing sheet using get_sheet_by_name (This errors: "NotImplementedError: use 'iter_rows()' instead".)
  2. Create a new sheet using create_sheet. (This errors:"ReadOnlyWorkbookException: Cannot create new sheet in a read-only workbook")

    df=DataFrame()
    from openpyxl.reader.excel import load_workbook
    book = load_workbook('my_excel_file.xlsx', use_iterators=True) # Assume my_excel_file.xlsx contains a sheet called 'Data'
    class temp_excel_writer(ExcelWriter): # I need this to inherit the other methods of ExcelWriter in io/parsers.py
    def __init__(self, path, book):
        self.book=book
        test_sheet=self.book.create_sheet(title='Test') # This errors: ReadOnlyWorkbookException
        self.use_xlsx = True
        self.sheet_names=self.book.get_sheet_names()
        self.actual_sheets=self.book.worksheets
        self.sheets={}
        for i,j in enumerate(self.sheet_names):
          self.sheets[j] = (self.actual_sheets[i],1)
        self.cur_sheet = None
        self.path = save
    my_temp_writer=temp_excel_writer('my_excel_file.xlsx', book)
    df.to_excel(my_temp_writer, sheet_name='Data')
    

Any thoughts? Am I missing something obvious? I'm still in pandas 7.2

1 Answers
Related