How to inherit openpyxl.Workbook and read in an xlsx file into an instance of the inherited class?

Viewed 271

I defined a class like so:

import openpyxl

class xlWorkbookTeX(openpyxl.Workbook):

    def __init__(self, filename):
        super().__init__()
        self.filename = filename
...

My purpose is to extend the Workbook class with added functionality (conversion to LaTeX tables), and this class seems most appropriate since it has all the functions I need to work with the contained worksheets etc.

But, strangely enough I cannot find a function to read in an existing xlsx file into the initialised Workbook instance within the Workbook class, although it does have a save method?!

The "official" way to load such data seems to be openpyx.load_workbook(), which returns a Workbook object. But how to get this data in my own xlWorkbookTeX instance?

I want to avoid the following:

  • add a Workbook member (it makes no sense, since I would be referring to a new Workbook instance under my inherited object, making the former obsolete)
  • copy over (or assigning) all data-holding members from the instance load_workbook() returned into my own object (I shouldn't have to care about the internals of the class, that's the reason I inherited from it in the first place)

Am I missing something obvious here? What would be the "correct" way to do this?

Thanks in advance!

EDIT:

since this seems less than trivial (let's call it strange architecture of this part of openpyxl?), I just took the shortcut I wanted to avoid:

def __init__(self, filename):
    super().__init__()
    # ok, awaiting a beter solution, just load and copy the data
    wb = openpyxl.load_workbook(filename=filename, data_only=True)
    self._sheets = wb._sheets
...

(This doesn't appear to be an issue since apparently there is no other data loaded than the sheets in my case. YMMV though.)

EDIT2:

The complete implementation using this is now at Github: xls2latex

0 Answers
Related