Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XlsxWriter object save as http response to create download in Django

XlsxWriter object save as http response to create download in Django?

like image 897
Waheed Avatar asked May 06 '13 06:05

Waheed


2 Answers

A little update on @alecxe response for Python 3 (io.BytesIO instead of StringIO.StringIO) and Django >= 1.5 (content_type instead of mimetype), with the fully in-memory file assembly that has since been implemented by @jmcnamara ({'in_memory': True}) !
Here is the full example :

import io  from django.http.response import HttpResponse  from xlsxwriter.workbook import Workbook   def your_view(request):      output = io.BytesIO()      workbook = Workbook(output, {'in_memory': True})     worksheet = workbook.add_worksheet()     worksheet.write(0, 0, 'Hello, world!')     workbook.close()      output.seek(0)      response = HttpResponse(output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")     response['Content-Disposition'] = "attachment; filename=test.xlsx"      output.close()      return response 
like image 150
Jeb Avatar answered Oct 05 '22 11:10

Jeb


I think you're asking about how to create an excel file in memory using xlsxwriter and return it via HttpResponse. Here's an example:

try:     import cStringIO as StringIO except ImportError:     import StringIO  from django.http import HttpResponse  from xlsxwriter.workbook import Workbook   def your_view(request):     # your view logic here      # create a workbook in memory     output = StringIO.StringIO()      book = Workbook(output)     sheet = book.add_worksheet('test')            sheet.write(0, 0, 'Hello, world!')     book.close()      # construct response     output.seek(0)     response = HttpResponse(output.read(), mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")     response['Content-Disposition'] = "attachment; filename=test.xlsx"      return response 

Hope that helps.

like image 28
alecxe Avatar answered Oct 05 '22 13:10

alecxe