Search code examples
pythonexcelioxlrd

Accepting an Excel file with io stream


Currently I am working on an Excel file and taking its path as input as

myObj = ProcessExcelFile("C:\SampleExcel.xlsx")

constructor is as

def __init__(self, filepath):
    '''
    Constructor
    '''
    if not os.path.isfile(filepath):
        raise FileNotFoundError(filepath)

    self.datawb = xlrd.open_workbook(filepath)

but now from another interface I want to use the same class but its not sending me filepath its sending me file through io stream as

data = req.stream.read(req.content_length)
file = io.BytesIO(data)

now this file variable when I am passing in my file as

myObj = ProcessExcelFile(file)

It's giving me error

TypeError: argument should be string, bytes or integer, not _io.BytesIO

I want to make my init so that it can take path as well as an io stream or if its not possible, I need to have file from io stream as priority


Solution

  • You would need to modify your class to allow streams as well. Pass the stream to open_workbook via file_contents.

    def __init__(self, filepath, stream=False):
        '''
        Constructor
        '''
        if stream:
            self.datawb = xlrd.open_workbook(file_contents=filepath.read())    
        else:        
            if not os.path.isfile(filepath):
                raise FileNotFoundError(filepath)
            self.datawb = xlrd.open_workbook(filepath)