Search code examples
pythonxlrd

xlrd API: get the owner of a lower level object (e.g. get the Sheet object from the Cell object)


I have a function that takes an xlrd.Cell object as an argument. However, the function also needs to access the xlrd.Sheet object which "owns" the cell. I'd prefer to not have to also pass the sheet object that it came from if I don't have to. Does the API provide a way to get at the sheet that owns the cell?

Accessing the xlrd.Book object from the sheet object would also be useful if that is possible.

I've looked closely at the API and it doesn't seem like these are available, but I'm notorious for overlooking things like this.


Solution

  • No. The definition of the xlrd.Cell object is:

    # Type:       Cell
    # String Form:number:42.0
    # File:       c:\python27\lib\site-packages\xlrd\sheet.py
    # Source:
    class Cell(BaseObject):
    
        __slots__ = ['ctype', 'value', 'xf_index']
    
        def __init__(self, ctype, value, xf_index=None):
            self.ctype = ctype
            self.value = value
            self.xf_index = xf_index
    
        def __repr__(self):
            if self.xf_index is None:
                return "%s:%r" % (ctype_text[self.ctype], self.value)
            else:
                return "%s:%r (XF:%r)" % (ctype_text[self.ctype], self.value, self.xf_index)
    

    So there are no reference to the parent Worksheet in the Cell object. You may easily extend xlrd.Worksheet and xlrd.Cell classes to add such reference, but you could just pass the parent Worksheet as well to your function and spare yourself the trouble.