首页 > 解决方案 > 通过 Django 的 StreamingHttpResponse 下载的 Excel 文件在打开时显示“格式无效”

问题描述

Django 2.2.5 | Python 3.6.12

我正在尝试使用通过熊猫的字典列表创建一个 xlsx 文件以供下载。由于文件可能会变得很大,我使用 StreamingHttpResponse() 而不是普通的 HttpResponse()。我当前下载文件但显示文件格式的代码在我尝试打开时无效。到目前为止,我已经提到了这两个链接:

https://docs.djangoproject.com/en/3.1/howto/outputting-csv/#streaming-large-csv-files

Django Pandas 到 http 响应(下载文件)

这是我目前正在使用的代码:

# 'emails' is the list of dictionaries
# 'list_name' contains the name of file

with BytesIO() as bio:
    writer = pd.ExcelWriter(bio, engine='xlsxwriter')
    dataframe = pd.DataFrame(data=emails)
    dataframe.to_excel(writer, sheet_name="Verify Results")
    writer.save()

    bio.seek(0)
    workbook = bio.getvalue()

    response = StreamingHttpResponse(
                workbook,
                content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            )
    response['Content-Disposition'] = f"attachment; filename={list_name}.xlsx"

    return response

但是,如果我使用

response = HttpResponse(
    bio,
    content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)

它下载并正确打开。

如何将 StreamingHttpResponse 与 pandas 一起使用,以便正确下载?

标签: pythondjangopandasxlsx

解决方案


推荐阅读