【Python】fastapi实现后端导出Excel

fastapi实现后端导出Excel

众所众知在CRM系统中常见的功能是查询,如果要把查询的结果本地化就需要导出数据至Excel了,导出前端后端都可以做,前端来做,就是接收后端数据加工成数据流形式再保存在Excel中;后端做的过程差不多,也是先将数据处理好,结果成数据流,借助第三方包来完成数据导出,今天主要谈谈后者,代码也比较简单,跟着代码去学习:

from fastapi import FastAPI, Response
from fastapi.responses import StreamingResponse
import pandas as pd
import io
import xlsxwriter

app = FastAPI()

@app.get("/")
async def download_excel():
    # 生成一个简单的 DataFrame
    data = {"name": ["Alice", "Bob", "Charlie"], "age": [25, 30, 35]}
    df = pd.DataFrame(data)

    # 将 DataFrame 转换为 Excel 文件
    buffer = io.BytesIO()
    workbook = xlsxwriter.Workbook(buffer)
    worksheet = workbook.add_worksheet()
    for i, col in enumerate(df.columns):
        worksheet.write(0, i, col)
        for j, value in enumerate(df[col]):
            worksheet.write(j + 1, i, value)
    workbook.close()

    # 将 Excel 文件转换为字节流,作为响应体返回给客户端
    buffer.seek(0)
    excel_bytes = buffer.getvalue()
    return StreamingResponse(io.BytesIO(excel_bytes), media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", headers={"Content-Disposition": "attachment; filename=myfile.xlsx"})


if __name__ == '__main__':
    import uvicorn

    # 官方推荐是用命令后启动 uvicorn main:app --host=127.0.0.1 --port=8000 --reload
    uvicorn.run(app='demo3:app', host="127.0.0.1", port=8010, reload=True)

浏览器请求:http://127.0.0.1:8010/

就会自动下载Excel文件到本地了,就是这么简单,感兴趣的小伙伴可以自己试试咯~

你可能感兴趣的:(实用工具,Python,职场,python,fastapi,excel)