使用 xlrd 打开 BytesIO (xlsx)

Open BytesIO (xlsx) with xlrd

我正在使用 Django,需要读取上传的 xlsx 文件的工作表和单元格。 xlrd 应该可以,但是因为文件必须保留在内存中并且可能无法保存到某个位置,所以我不确定如何继续。

本例中的起点是一个带有上传输入和提交按钮的网页。提交后,文件被 request.FILES['xlsx_file'].file 捕获并发送到处理程序 class,该处理程序必须提取所有重要数据以进行进一步处理。

request.FILES['xlsx_file'].file 的类型是 BytesIO,由于没有 getitem 方法,xlrd 无法读取该类型。

将 BytesIO 转换为 StringIO 后,错误消息似乎保持不变 '_io.StringIO' object has no attribute '__getitem__'

    file_enc = chardet.detect(xlsx_file.read(8))['encoding']
    xlsx_file.seek(0)

    sio = io.StringIO(xlsx_file.read().decode(encoding=file_enc, errors='replace'))
    workbook = xlrd.open_workbook(file_contents=sio)

尝试xlrd.open_workbook(file_contents=request.FILES['xlsx_file'].read())

我正在将我的评论移动到它自己的答案中。它与更新问题中给出的示例代码(包括解码)有关:

好的,谢谢指点。我下载了xlrd,在本地测试了一下。似乎去这里最好的方法是给它传递一个字符串,即。 open_workbook(file_contents=xlsx_file.read().decode(encoding=file_enc, errors='replace'))。我误解了文档,但我很肯定 file_contents= 可以使用字符串。

我遇到了类似的问题,但在我的情况下,我需要对 Djano 应用程序进行单元测试,并由用户下载 xls 文件。

使用 StringIO 的基本代码对我有用。

class myTest(TestCase):
    def test_download(self):
        response = self.client('...')
        f = StringIO.StringIO(response.content)
        book = xlrd.open_workbook(file_contents = f.getvalue() )
        ...
        #unit-tests here