我正在使用Django,需要读取上传的xlsx文件的工作表和单元格。使用xlrd应该是可能的,但是由于文件必须保存在内存中,并且可能不会保存到某个位置,所以我不知道如何继续。
本例中的起点是一个带有上传输入和提交按钮的网页。当提交该文件时,将使用request.FILES['xlsx_file'].file
捕获该文件,并将其发送到一个处理类,该类必须提取所有重要数据以供进一步处理。
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)
发布于 2016-04-07 10:26:04
我要把我的评论变成自己的答案。它与更新问题中给出的示例代码(包括解码)有关:
好的,谢谢你的指点。我下载了xlrd并在本地进行了测试。看来最好的办法就是给它一根绳子。open_workbook(file_contents=xlsx_file.read().decode(encoding=file_enc, errors='replace'))
。我误解了文档,但我确信file_contents=将使用字符串。
发布于 2016-04-07 10:19:37
试试xlrd.open_workbook(file_contents=request.FILES['xlsx_file'].read())
发布于 2017-05-17 17:02:05
我也有类似的问题,但在我的例子中,我需要用xls文件的用户下载的Djano应用程序进行单元测试。
使用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
https://stackoverflow.com/questions/36472681
复制相似问题