Reputation: 3756
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?
Upvotes: 1
Views: 455
Reputation: 17506
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
Upvotes: 2