【问题标题】:How to return xlsx file from memory in fastapi?如何在fastapi中从内存中返回xlsx文件?
【发布时间】:2020-08-18 08:55:08
【问题描述】:

我想根据要求提供 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.

我该如何解决这个问题?

【问题讨论】:

    标签: python-3.x xlsxwriter fastapi bytesio


    【解决方案1】:

    您必须在响应中设置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)

    【讨论】:

      猜你喜欢
      • 2022-09-24
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-10
      相关资源
      最近更新 更多