使用 xlrd 打开 BytesIO (xlsx) [英] Open BytesIO (xlsx) with xlrd

查看:86
本文介绍了使用 xlrd 打开 BytesIO (xlsx)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working with Django and need to read the sheets and cells of an uploaded xlsx file. It should be possible with xlrd but because the file has to stay in memory and may not be saved to a location I'm not sure how to continue.

在这种情况下,起点是一个带有上传输入和提交按钮的网页.提交后,文件被 request.FILES['xlsx_file'].file 捕获并发送到处理类,该类必须提取所有重要数据以供进一步处理.

The start point in this case is a web page with an upload input and a submit button. When submitted the file is caught with request.FILES['xlsx_file'].file and send to a processing class that would have to extract all the important data for further processing.

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

The type of request.FILES['xlsx_file'].file is BytesIO and xlrd is not able to read that type because of no getitem methode.

将 BytesIO 转换为 StringIO 后,错误消息似乎保持不变 '_io.StringIO' 对象没有属性 '__getitem__'

After converting the BytesIO to StringIO the error messages seems to stay the same '_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)

推荐答案

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

I'm moving my comment into an answer of it's own. It related to the example code (which includes decoding) given in the updated question:

好的,谢谢你的指点.我下载了 xlrd 并在本地进行了测试.似乎最好的方法是传递一个字符串,即.open_workbook(file_contents=xlsx_file.read().decode(encoding=file_enc, errors='replace')).我误解了文档,但我确信 file_contents= 可以使用字符串.

Ok, thanks for your pointers. I downloaded xlrd and tested it locally. It seems the best way to go here is to pass it a string ie. open_workbook(file_contents=xlsx_file.read().decode(encoding=file_enc, errors='replace')). I misunderstood the docs, but I'm positive that file_contents= will work with a string.

这篇关于使用 xlrd 打开 BytesIO (xlsx)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆