如何在 fastapi 中从内存中 return xlsx 文件?

How to return xlsx file from memory in fastapi?

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

    <b>headers = {
        'Content-Disposition': 'attachment; filename="filename.xlsx"'
    }</b>
    return StreamingResponse(output, <b>headers=headers</b>)