Python读取excel并形成api接口案例
·
from fastapi import FastAPI, HTTPException
import pandas as pd
import uvicorn
import configparser
import os
app = FastAPI(title="Excel读取API", version="1.0")
# 读取配置文件
current_dir = os.path.dirname(os.path.abspath(__file__))
config_path = os.path.join(current_dir, "config.ini")
config = configparser.ConfigParser()
config.read(config_path, encoding="utf-8")
EXCEL_FILE_PATH = config["EXCEL"]["file_path"]
# API接口
@app.get("/read-excel")
def read_excel(sheet_name: str | int = 0):
try:
df = pd.read_excel(EXCEL_FILE_PATH, sheet_name=sheet_name, engine="openpyxl")
return {
"code": 200,
"msg": "读取成功",
"columns": df.columns.tolist(),
"data": df.to_dict("records")
}
except FileNotFoundError:
raise HTTPException(status_code=404, detail=f"文件不存在:{EXCEL_FILE_PATH}")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8002)更多推荐




所有评论(0)