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

基于Azure Function的API如何通过Post请求返回Excel文件?

修改Azure Function实现返回Excel文件

要实现Post请求返回Excel文件,需完成以下关键修改:

1. 添加依赖库

在项目的requirements.txt中补充处理Excel的依赖,pandas配合openpyxl(支持标准xlsx格式)即可:

azure-functions
pandas
openpyxl

2. 调整核心代码

替换原有生成CSV的逻辑,改用内存对象存储Excel二进制数据,同时更新响应头与MIME类型:

from io import BytesIO
import pandas as pd
import azure.functions as func
import logging

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    response = req.get_json()
    
    # 保留原有SQL语句生成逻辑
    statement = # sql statement using payload data from post request
    df = rpt.sql_table_to_df(statement)
    
    # 用BytesIO在内存中生成Excel文件
    output = BytesIO()
    with pd.ExcelWriter(output, engine='openpyxl') as writer:
        df.to_excel(writer, index=False, sheet_name='Report')
    # 重置文件指针到起始位置,确保能读取完整数据
    output.seek(0)
    
    # 更新响应头信息
    headers = {
        "Content-Disposition": "attachment; filename='report.xlsx'",
        "Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    }
    
    return func.HttpResponse(body=output.getvalue(), status_code=200, headers=headers)

关键修改说明

  • 引入BytesIO:避免写入本地磁盘(Azure Function无持久化本地存储),直接在内存中生成Excel文件
  • 替换to_csv为to_excel:通过ExcelWriter将DataFrame写入内存对象,支持多工作表、格式设置等扩展需求
  • 调整响应参数:
    • 修改Content-Disposition中的文件后缀为.xlsx
    • 替换MIME类型为Excel专属的application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
  • 重置指针:写入Excel后必须将BytesIO的指针移到开头,否则返回的内容为空

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 01:24:30