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)
相关推荐
羲云网络2 小时前
GPT Image 2.6 海报改横竖版:文字安全区、排版分离与交付验收
图像处理·人工智能·python·aigc
曲径海盗4 小时前
【Python 学习第 65 天】字典基础
python·学习笔记·编程入门
Wellijohn4 小时前
Docker 瘦身、手写 MCP、异步并发:被问得最多的 12 个问题,一次答完
python·docker·mcp
VW_4047 小时前
csdn-2026-11-23-第一站踩坑
爬虫·python
yiangL_7 小时前
课后作业4:基于 Python 的古诗词词云可视化(P205)
开发语言·python
Dmz丶7 小时前
前端转 AI 100 天 Day 52:RAG 项目实战(一)——从零搭建企业知识库
python
卷无止境11 小时前
用 SimPy 做离散事件仿真:时钟不走步,事件自己排队
后端·python
撸码猿12 小时前
数据采集场景的语序点选验证码:90.2% 整词准确率的本地 OCR 实践
python·ocr
用户03321266636712 小时前
使用 Python 在 Excel 中创建折线图和条形图
python·excel
木子欢儿13 小时前
Ubuntu 26.04 LTS 安装Python 3.12
linux·运维·服务器·python·ubuntu