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)
Logo

小龙虾开发者社区是 CSDN 旗下专注 OpenClaw 生态的官方阵地,聚焦技能开发、插件实践与部署教程,为开发者提供可直接落地的方案、工具与交流平台,助力高效构建与落地 AI 应用

更多推荐