python - 通过 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
这是我目前正在使用的代码:
# '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 一起使用,以便正确下载?
解决方案
推荐阅读
- node.js - Bitbucket Pipeline npm install 失败并显示“npm ERR!致命:无法访问”
- javascript - 如何在反应原生地图中获取边界
- android - 地点 ID 不提供与谷歌地图使用的相同类别
- sql - Wordpress:使用 get_results 检查数据
- python - 使用 BeautifulSoup 在 xml 解析中删除包含特定子标签的标签
- php - 嵌套单选按钮
- xamarin.ios - Amazon Cognito 身份错误:“无法存储密钥”Xamarin.iOS
- vagrant - vagrant smb 共享文件中的文件内容混乱
- php - 将 WordPress 个人资料 Gravatar 更改为生成的 robohash
- c# - if 语句有多个条件,而不是使用 AND