V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
dwadewyp
V2EX  ›  Python

django 导出 excel 问题 求助

  •  
  •   dwadewyp · 2020-09-16 17:28:30 +08:00 · 1659 次点击
    这是一个创建于 1289 天前的主题,其中的信息可能已经有所发展或是发生改变。
    我想实现 通过调取 django 的 api,然后下载一个 excel 文件, 不过目前遇到的情况是,返回了乱码的字节流,并不是文件,求助
    13 条回复    2020-09-22 16:14:54 +08:00
    manzhiyong
        1
    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
        2
    dwadewyp  
    OP
       2020-09-16 17:33:48 +08:00
    @manzhiyong 我就是这么做的。。。 通过 postman 返回的是乱码的字节流
    dwadewyp
        3
    dwadewyp  
    OP
       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
        4
    bolide2005  
       2020-09-16 17:36:19 +08:00
    content type 改成 application/x-xls 试试?
    manzhiyong
        5
    manzhiyong  
       2020-09-16 17:38:00 +08:00
    dwadewyp
        6
    dwadewyp  
    OP
       2020-09-16 17:41:19 +08:00
    @manzhiyong 感谢
    sunmlight
        7
    sunmlight  
       2020-09-16 20:47:29 +08:00
    有可能是文件名的原因, 可以 urlquote 转一下文件名
    Erroad
        8
    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
        9
    renmu123  
       2020-09-16 20:52:30 +08:00 via Android
    你用 requests 請求處理一下文件試試看
    Erroad
        10
    Erroad  
       2020-09-16 20:52:42 +08:00
    这是用 google 搜到的 mdn 对 xls,slsx mime 类型的描述,但是怀疑也可能不是这个原因?
    hushao
        11
    hushao  
       2020-09-17 08:46:36 +08:00 via iPhone
    你用 postman 看二进制文件当然是乱码...
    vegetableChick
        12
    vegetableChick  
       2020-09-22 16:10:12 +08:00
    postman 不是可以直接 post_and_save 么?
    dwadewyp
        13
    dwadewyp  
    OP
       2020-09-22 16:14:54 +08:00
    @vegetableChick 已解决
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3065 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 12:50 · PVG 20:50 · LAX 05:50 · JFK 08:50
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.