You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI读取上传Excel文件报错:需手动指定引擎,求排查

FastAPI上传Excel文件解析报错的解决方法

你的读取方式存在两处问题,导致pandas无法识别Excel格式,以下是具体解决思路和修正代码:

问题原因

  1. UploadFile的文件对象指针可能处于文件末尾,pandas读取不到有效内容
  2. 直接传递文件对象时,pandas无法自动推断Excel文件格式,需要手动指定解析引擎

解决步骤

  • 先重置文件指针到起始位置:调用file.file.seek(0),确保pandas从文件开头读取
  • 根据Excel文件后缀(.xlsx/.xls)指定对应的解析引擎:
    • 处理.xlsx文件用engine="openpyxl"(需提前安装:pip install openpyxl)
    • 处理.xls文件用engine="xlrd"(需安装xlrd 1.2.0版本,因为2.0+不再支持.xlsx)

修正后的完整代码

from fastapi import FastAPI, File, UploadFile
import pandas as pd
import uuid

app = FastAPI()

@app.post("/upload-excel/")
def upload_excel_parser(file: UploadFile = File(...)):
    s_filename = file.filename
    unique_id = str(uuid.uuid4())
    project_id = s_filename + unique_id
    
    # 重置文件指针到开头
    file.file.seek(0)
    # 根据文件名后缀选择引擎
    if s_filename.endswith(".xlsx"):
        df = pd.read_excel(file.file, engine="openpyxl")
    elif s_filename.endswith(".xls"):
        df = pd.read_excel(file.file, engine="xlrd")
    else:
        return {"error": "不支持的文件格式,请上传.xlsx或.xls文件"}
    
    return {"status": "success", "project_id": project_id, "row_count": len(df)}

额外注意事项

  • 务必提前安装对应的解析引擎依赖,否则会出现引擎找不到的报错
  • 可以增加文件格式校验,避免用户上传非Excel文件

内容的提问来源于stack exchange,提问作者devb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 14:42:44