Skip to content

Instantly share code, notes, and snippets.

@martync
Created February 9, 2012 14:40
Show Gist options
  • Save martync/1780405 to your computer and use it in GitHub Desktop.
Save martync/1780405 to your computer and use it in GitHub Desktop.
Output an XLS file with XLWT
from django.template import Variable, defaultfilters
from django.http import HttpResponse
import xlwt
def render_to_xls(queryset, filename, fields):
"""
Output an XLS file of the queryset
Usage :
-------
queryset = Book.objects.all()
fields = (
('Author', 'author.get_full_name'),
('Release date', 'release_date|date:"Y-m-d"'),
('Title', 'title|title')
)
filename = "BooksDB"
return render_to_xls(
queryset=queryset,
filename=filename,
fields=fields
)
"""
ezxf = xlwt.easyxf
book = xlwt.Workbook(encoding="utf-8")
sheet = book.add_sheet("Feuille 1")
# Set title styles
heading_xf = ezxf('font:name Verdana, bold on; align: wrap on, vert centre, horiz center;pattern: fore_color green ;')
i, j = 0, 0
# Write the titles on the first line
for f in fields:
sheet.write(i, j, f[0], heading_xf)
j+=1
for object in queryset:
i += 1
j = 0
context = {'object': object}
for f in fields:
# I did not find yet a django stuff to
# deal with templatefilter
chains = str("object.%s" % f[1]).split("|")
var = chains[0]
# We resolve the var to get raw data
data = Variable(var).resolve(context)
# If we have filters, we apply them
# TODO : If django has a method to deal
# with it, jsut do it
for chain in chains[1:]:
filter_nameargs = chain.split(':')
filter_name = filter_nameargs[0]
template_filter = getattr(defaultfilters, filter_name)
if len(filter_nameargs)>1:
args = filter_nameargs[1].replace('"', '')
data = template_filter(data, args)
else:
data = template_filter(data)
# Finally we write the data on the sheet
sheet.write(i, j, u"%s" % data)
j+=1
response = HttpResponse(mimetype='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=%s.xls' % filename
book.save(response)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment