Python 接受带有io流的Excel文件

Python 接受带有io流的Excel文件,python,excel,io,xlrd,Python,Excel,Io,Xlrd,目前我正在处理一个Excel文件,并将其路径作为输入 myObj = ProcessExcelFile("C:\SampleExcel.xlsx") 构造函数如下所示 def __init__(self, filepath): ''' Constructor ''' if not os.path.isfile(filepath): raise FileNotFoundError(filepath) self.datawb = xlrd.

目前我正在处理一个Excel文件,并将其路径作为输入

myObj = ProcessExcelFile("C:\SampleExcel.xlsx")
构造函数如下所示

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

    self.datawb = xlrd.open_workbook(filepath)
但是现在从另一个接口,我想使用同一个类,但它不向我发送文件路径,而是通过io流向我发送文件

data = req.stream.read(req.content_length)
file = io.BytesIO(data)
现在,当我以

myObj = ProcessExcelFile(file)
这给了我错误

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

我想使我的init可以采用path和io流,或者如果不可能,我需要将io流中的文件作为优先级

您需要修改类以允许流。通过
file\u contents
将流传递到
open\u工作簿

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)

您还需要修改类以允许流。通过
file\u contents
将流传递到
open\u工作簿

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)

在这种情况下,如果我传递一个流,它仍然会落在FileNotFoundException中,对吗?我需要把它放在其他部分吗?是的,我刚刚意识到同样的复制粘贴错误。我会更新答案的,成功了!很多坦克!我很抱歉,但这个简单的事情,我无法谷歌它正确在这种情况下,如果我通过一个流,它仍然会在文件中未找到异常的权利?我需要把它放在其他部分吗?是的,我刚刚意识到同样的复制粘贴错误。我会更新答案的,成功了!很多坦克!我很抱歉,但这个简单的事情我无法谷歌它正确