简体   繁体   中英

Downloading a file with django

I am trying to download a xlsl file generated with xlsxwriter using django. I have written code like this many times before, but not with xlsxwriter (with csvwriter) and it's worked fine. But in the case, when I download the file it is always empty. But the file on the file system is not.

Here is my view code:

def download_xls(self, request):
    os.chdir('/tmp')
    xls_name = re.sub('\s+', '_', "%s_%s_%s.xlsx" % (
        request.user.username.lower(),
        self.report.name.lower(),
        datetime.now().strftime('%y%m%d_%H%I%S')))

    workbook = xlsxwriter.Workbook(xls_name)
    worksheet1 = workbook.add_worksheet()
    worksheet2 = workbook.add_worksheet()

    worksheet1.write("A1", "hello1")
    worksheet2.write("A1", "hello2")

    workbook.close()
    response = HttpResponse(content_type='application/ms-excel')
    response['Content-disposition'] = "attachment; filename=%s" % xls_name
    return response

Here is the file on the file system:

-rw-r--r--  1 _www            wheel   5751 Oct 24 09:14 /tmp/admin_wafer_viz_151024_090900.xlsx

And here is the downloaded file:

-rw-------@   1 LarryMartell  staff      0 Oct 24 09:14 admin_wafer_viz_151024_090900.xlsx

Can anyone see what probably stupid simple thing I am doing wrong here?

You need to save the workbook to the response to put the actual file into the HTTP response:

def download_xls(self, request):
    os.chdir('/tmp')
    xls_name = re.sub('\s+', '_', "%s_%s_%s.xlsx" % (
        request.user.username.lower(),
        self.report.name.lower(),
        datetime.now().strftime('%y%m%d_%H%I%S')))
    output = io.BytesIO()

    workbook = Workbook(output, {'in_memory': True})
    worksheet1 = workbook.add_worksheet()
    worksheet2 = workbook.add_worksheet()

    worksheet1.write("A1", "hello1")
    worksheet2.write("A1", "hello2")

    workbook.close()

    output.seek(0)

    response = HttpResponse(content_type='application/ms-excel')
    response['Content-disposition'] = "attachment; filename=%s" % xls_name

    return response

You can also try the xlwt package which seems more straightforward:

workbook.save(response)
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = "attachment; filename=%s" % xls_name

You can see an example on one of my projects here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM