首页 > 解决方案 > 如何通过 POST 表单接收 Excel 文件,然后用 pandas 打开它?(Python3 aiohttp)

问题描述

我正在尝试使用以下形式从用户那里获取文件:

<form enctype="multipart/form-data" action="/demo" method="POST">
    <div class="form-group">
        <input type="file" name="myfile" id="file">
    </div>
    <button class="btn btn-primary btn-lg" type="submit">Add Excel</button>
</form>

在我看来.py

当我使用file = post.get("myfile")然后打印它时,我得到以下信息:

FileField(name='myfile', filename='file.xlsx', file=<_io.BufferedRandom name=12>, 
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 
headers=<CIMultiDictProxy('Content-Disposition': 'form-data; name="myfile"; 
filename="file.xlsx"', 'Content-Type': 'application/vnd.openxmlformats- 
officedocument.spreadsheetml.sheet')>)

但是当我尝试用 pandas 创建一个 DataFrame 时,df = pandas.read_excel(file, header= None, dtype=str)我得到:

Error handling request
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/web_protocol.py", line 422, in _handle_request
    resp = await self._request_handler(request)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/web_app.py", line 499, in _handle
    resp = await handler(request)
  File "/Users/ricardonunez/code/OCE/LocalVersion/Service/views.py", line 20, in upload_file
    db.processF(file1)
  File "/Users/ricardonunez/code/OCE/LocalVersion/Service/db.py", line 757, in processF
    df = pandas.read_excel(fr, header= None, dtype=str)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/util/_decorators.py", line 299, in wrapper
    return func(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/io/excel/_base.py", line 336, in read_excel
    io = ExcelFile(io, storage_options=storage_options, engine=engine)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/io/excel/_base.py", line 1071, in __init__
    ext = inspect_excel_format(
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/io/excel/_base.py", line 949, in inspect_excel_format
    with get_handle(
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/io/common.py", line 558, in get_handle
    ioargs = _get_filepath_or_buffer(
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/io/common.py", line 371, in _get_filepath_or_buffer
    raise ValueError(msg)
ValueError: Invalid file path or buffer object type: <class 'aiohttp.web_request.FileField'>

我是否正确接收文件?如何使用 pandas 创建文件的 DataFrame?

标签: pythonpandaspostaiohttp

解决方案


您需要在收到文件后保存文件。打印时得到的只是它在 Web 服务器中的内存表示。有关在 Django 中处理上传的更多信息:上传


推荐阅读