gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 09:05:00 25 4
gpt4 key购买 nike

我想应要求提供 xlsx。随着使用 BytesIOxlsxwriter我创建一个文件。
使用下面的代码,我可以下载一个空的(!).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-officedocument.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.
我该如何解决这个问题?

最佳答案

您必须设置 Content-Disposition 响应中的 header

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

关于python-3.x - 如何在fastapi中从内存中返回xlsx文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63465155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com