This post will show you how to extend the django admin to allow for any model to be exported to an excel spreadsheet. it uses the xlwt module to generate the spreadsheet.
views.py
def admin_export_xls(request, app, model): mc = ContentType.objects.get(app_label=app, model=model).model_class() wb = xlwt.Workbook() ws = wb.add_sheet(unicode(mc._meta.verbose_name_plural)) for i, f in enumerate(mc._meta.fields): ws.write(0,i, f.name) qs = mc.objects.all() for ri, row in enumerate(qs): for ci, f in enumerate(mc._meta.fields): ws.write(ri+1, ci, unicode(getattr(row, f.name))) fd, fn = tempfile.mkstemp() os.close(fd) wb.save(fn) fh = open(fn, 'rb') resp = fh.read() fh.close() response = HttpResponse(resp, mimetype='application/ms-excel') response['Content-Disposition'] = 'attachment; filename=%s.xls' % \ (unicode(mc._meta.verbose_name_plural),) return response
because the xlwt module doesn't allow you to write to an open file handle, we have to first create a temporary file using tempfile.mkstemp() and subsequently close the file, then save spreadsheet with the returned filename. This might not be the most efficient way, but it works.
in the urls file we need to point to the new view, be sure to put this line before the regular admin include since it acts as a sort of catch-all. [Update: Wrapped the view in admin.site.admin_view decorator.] urls.py
... (r'^admin/([^\/]+)/([^\/]+)/xls/$', admin_export_xls), (r'^admin/(.*)', admin.site.admin_view(admin.site.root)), ...
Now we need to add a button to the top of each change list template that we want to have this functionality.
change_list.html
{% extends 'admin/change_list.html' %}{% load i18n %}
{% block object-tools %}
<ul class="object-tools">
{% if has_add_permission %}
<li>
<a href="add/{% if is_popup %}?_popup=1{% endif %}" class="addlink">
{% blocktrans with cl.opts.verbose_name as name %}Add {{ name }}{% endblocktrans %}
</a>
</li>
{% endif %}
<li>
<a href="xls/" class="viewsitelink">Export to .XLS</a>
</li>
</ul>
{% endblock %}
Comments/suggestions appreciated.
RSS
2009 April 10, 8:37 PM
2009 April 11, 8:52 AM
2009 April 14, 2:35 PM
2009 April 30, 12:31 AM
2009 May 05, 6:19 PM