POST上传的excel(xls)文件,如何直接读进pandas,避免写入到磁盘?

csv文件我可以这样写代码,已测试没有问题。
但是execl文件用TextIOWrapper好像不行。

    if form.validate_on_submit():
        if request.method == 'POST':
            for file in request.files.getlist("files"):
                if file:
                    csvfile = io.TextIOWrapper(file.stream, encoding='gbk')
                    reader = csv.reader(csvfile)
                    for line in reader:
                        temp = line[0]

然而我pandas读取excel的时候:

form = ShopDataForm()
    if form.validate_on_submit():
        if request.method == 'POST':
            file = request.files['files']
            execlfile = io.TextIOWrapper(file.stream)
            taxidata_from_excel = pd.read_excel(execlfile, header=0, encoding='gbk')

报错:
builtins.UnicodeDecodeError
UnicodeDecodeError: 'gbk' codec can't decode byte 0xba in position 22: illegal multibyte sequence
编码这里我换了gbk,utf-8都不行

但是当我尝试着本地读取的话,简单一句就能成功读取了。。

temp=pd.read_excel("1.xls")

所以到底是哪里出了问题?

阅读 10.2k
2 个回答

.xls不是文本文件, 设置encoding应该是无效的。
老老实实等文件下载完,再 pd.read_excel()


read_excel(io)
io可以是 url、ftp 之类的资源定位符。
如果你知道.xls的位置,可以直接打开。

>>>help(pd.read_excel)
Help on function read_excel in module pandas.io.excel:

read_excel(io, …………)
    Read an Excel table into a pandas DataFrame
    
    Parameters
    ----------
    io : string, path object (pathlib.Path or py._path.local.LocalPath),
        file-like object, pandas ExcelFile, or xlrd workbook.
        The string could be a URL. Valid URL schemes include http, ftp, s3,
        and file. For file URLs, a host is expected. For instance, a local
        file could be file://localhost/path/to/workbook.xlsx

试一下,直接 pd.read_excel(file) 或 (file.stream)

file = request.files['files']
taxidata_from_excel = pd.read_excel(file) # (file.stream)

我觉得 stringIO 可以解决你的问题 。用它来先保存下file.stream 内容。在传给pd。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题