Serving Excel(xlsx) file to the user for download in Django(Python)

为君一笑 提交于 2019-12-04 04:54:20

In addition to what Bruno says, you probably need to open the file in binary mode:

excel = open("%s_Report.xlsx" % id, "rb")

Why on earth are you passing your file's content to a StringIO just to assign StringIO.get_value() to a local variable ? What's wrong with assigning file.read() to your variable directly ?

def generateExcel(request,id):
    path = './%s_Report.xlsx' % id # this should live elsewhere, definitely
    if os.path.exists(path):
        with open(path, "r") as excel:
            data = excel.read()

        response = HttpResponse(data,content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        response['Content-Disposition'] = 'attachment; filename=%s_Report.xlsx' % id
        return response
    else:
        # quite some duplication to fix down there

Now you may want to check weither you actually had any content in your file - the fact that the file exists doesn't mean it has anything in it. Remember that you're in a concurrent context, you can have one thread or process trying to read the file while another (=>another request) is trying to write it.

Naren Yellavula

You can use this library to create excel sheets on the fly. http://xlsxwriter.readthedocs.io/

For more information see this page. Thanks to @alexcxe

XlsxWriter object save as http response to create download in Django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!