我想根据要求提供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-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
标头
@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)