接受带有 io 流的 Excel 文件

Accepting an Excel file with io stream

目前我正在处理一个 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)

但现在我想从另一个界面使用相同的 class 但它没有向我发送文件路径而是通过 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 可以获取路径和 io 流,或者如果不可能,我需要将来自 io 流的文件作为优先级

您需要修改 class 以允许流式传输。通过 file_contents.

将流传递给 open_workbook
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)