Login

Excel Export with xlwt

Author:
sspross
Posted:
October 12, 2010
Language:
Python
Version:
1.2
Tags:
excel xlwt
Score:
1 (after 3 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. Excel Date by cronosa 5 years ago
  2. ExcelResponse2 by Hackathon 11 months, 2 weeks ago
  3. UnicodeWriter and UnicodeDictWriter - write unicode strings out to Excel compatible CSV files by simon 6 years, 8 months ago
  4. Generic admin action to export data into excel/csv by vinay.chittora 1 year, 8 months ago
  5. Excel Spreadsheet Export by MasonM 6 years, 8 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.