Login

Excel Export with xlwt

Author:
sspross
Posted:
October 12, 2010
Language:
Python
Version:
1.2
Score:
2 (after 4 ratings)

how to generate a (real) excel file as an HTTP response with xlwt

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import xlwt

def tool_excel_export(self, request, obj, button):
    response = HttpResponse(mimetype="application/ms-excel")
    response['Content-Disposition'] = 'attachment; filename=file.xls'
    
    wb = xlwt.Workbook()
    ws = wb.add_sheet('Sheetname')
    
    ws.write(0, 0, 'Firstname')
    ws.write(0, 1, 'Surname')
    ws.write(1, 0, 'Hans')
    ws.write(1, 1, 'Muster')

    wb.save(response)
    return response

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

LuckiDog (on June 9, 2011):

IE seems to require that file.xls be "file.xls" Or it will puke saying it can't save the file if your url ends in a slash.

#

redglyph (on April 7, 2012):

The following is also missing:

from django.http import HttpResponse

Finally, the MIME type is wrong, it should be like this:

response = HttpResponse(mimetype="application/vnd.ms-excel")

#

Please login first before commenting.