django 导出 excel 问题 求助

2020-09-16 17:28:30 +08:00
 dwadewyp
我想实现 通过调取 django 的 api,然后下载一个 excel 文件, 不过目前遇到的情况是,返回了乱码的字节流,并不是文件,求助
1676 次点击
所在节点    Python
13 条回复
manzhiyong
2020-09-16 17:32:55 +08:00
from openpyxl import Workbook
....
....
wb = Workbook()
.....
......
response = HttpResponse(content_type='application/msexcel')
response['Content-Disposition'] = 'attachment; filename=xxx.xls'
wb.save(response)
return response
dwadewyp
2020-09-16 17:33:48 +08:00
@manzhiyong 我就是这么做的。。。 通过 postman 返回的是乱码的字节流
dwadewyp
2020-09-16 17:35:28 +08:00
@manzhiyong response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename="ThePythonDjango.xls"'
ws.save(response)
return response
bolide2005
2020-09-16 17:36:19 +08:00
content type 改成 application/x-xls 试试?
manzhiyong
2020-09-16 17:38:00 +08:00
dwadewyp
2020-09-16 17:41:19 +08:00
@manzhiyong 感谢
sunmlight
2020-09-16 20:47:29 +08:00
有可能是文件名的原因, 可以 urlquote 转一下文件名
Erroad
2020-09-16 20:51:05 +08:00
.xls Microsoft Excel application/vnd.ms-excel
.xlsx Microsoft Excel (OpenXML) application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
renmu123
2020-09-16 20:52:30 +08:00
你用 requests 請求處理一下文件試試看
Erroad
2020-09-16 20:52:42 +08:00
这是用 google 搜到的 mdn 对 xls,slsx mime 类型的描述,但是怀疑也可能不是这个原因?
hushao
2020-09-17 08:46:36 +08:00
你用 postman 看二进制文件当然是乱码...
vegetableChick
2020-09-22 16:10:12 +08:00
postman 不是可以直接 post_and_save 么?
dwadewyp
2020-09-22 16:14:54 +08:00
@vegetableChick 已解决

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/707638

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX