Python 3.x 如何在fastapi中从内存返回xlsx文件?

Python 3.x 如何在fastapi中从内存返回xlsx文件?,python-3.x,xlsxwriter,fastapi,bytesio,Python 3.x,Xlsxwriter,Fastapi,Bytesio,我想应要求提供xlsx。使用BytesIO和xlsxwriter我创建了一个文件 使用下面的代码,我可以下载一个空(!).txt文件: @router.get("/payments/xlsx", response_description='xlsx') async def payments(): """sss""" output = BytesIO() workbook = xlsxwrite

我想应要求提供xlsx。使用
BytesIO
xlsxwriter
我创建了一个文件

使用下面的代码,我可以下载一个空(!)
.txt
文件:

@router.get("/payments/xlsx", response_description='xlsx')
async def payments():
    """sss"""
    output = BytesIO()
    workbook = xlsxwriter.Workbook(output)
    worksheet = workbook.add_worksheet()
    worksheet.write(0, 0, 'ISBN')
    worksheet.write(0, 1, 'Name')
    worksheet.write(0, 2, 'Takedown date')
    worksheet.write(0, 3, 'Last updated')
    workbook.close()
    output.seek(0)
    return StreamingResponse(output)
如果我添加
headers={'Content-Type':'application/vnd.openxmlformats of cedocument.spreadsheetml.sheet}
我在浏览器中会遇到以下错误:

Unable to open file
You may be having a problem connecting with the server, or the file that you wanted to open was corrupted.
如何解决此问题?

您必须在响应中设置标题

@router.get("/payments/xlsx", response_description='xlsx')
async def payments():
    output = BytesIO()
    workbook = xlsxwriter.Workbook(output)
    worksheet = workbook.add_worksheet()
    worksheet.write(0, 0, 'ISBN')
    worksheet.write(0, 1, 'Name')
    worksheet.write(0, 2, 'Takedown date')
    worksheet.write(0, 3, 'Last updated')
    workbook.close()
    output.seek(0)

    headers = {
        'Content-Disposition': 'attachment; filename="filename.xlsx"'
    }
    return StreamingResponse(output, headers=headers)
@router.get(“/payments/xlsx”,response\u description='xlsx')
异步def支付():
输出=BytesIO()
工作簿=xlsxwriter.工作簿(输出)
工作表=工作簿。添加工作表()
工作表。写入(0,0,'ISBN')
工作表。写入(0,1,‘名称’)
工作表。写入(0,2,‘拆卸日期’)
工作表。写入(0,3,“上次更新”)
工作簿.关闭()
输出搜索(0)
标题={
“内容处置”:“附件;文件名=“filename.xlsx””
}
返回StreamInResponse(输出,标题=标题)