Django Pandas to http response (download file)

前端 未结 6 959
醉话见心
醉话见心 2020-12-29 06:36

Python: 2.7.11

Django: 1.9

Pandas: 0.17.1

How should I go about creating a potentially large xlsx file download? I\'m creating a xlsx file with panda

6条回答
  •  一生所求
    2020-12-29 07:12

    Maybe a bit off-topic, but it's worth pointing out that the to_csv method is generally faster than to_excel, since excel contains format information of the sheets. If you only have data and not formatting information, consider to_csv. Microsoft Excel can view and edit csv files with no problem.

    One gain by using to_csv is that to_csv function can take any file-like object as the first argument, not only a filename string. Since Django response object is file-like, to_csv function can directly write to it. Some codes in your view function will look like:

    df = 
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename='
    df.to_csv(response, index=False)
    return response
    

    Reference:

    1. https://gist.github.com/jonperron/733c3ead188f72f0a8a6f39e3d89295d
    2. https://docs.djangoproject.com/en/2.1/howto/outputting-csv/

提交回复
热议问题