Skip to content

Instantly share code, notes, and snippets.

@snahor
Created Jan 4, 2012
Embed
What would you like to do?
Django admin export all the records of the current queryset to XLS
import xlwt
from django.http import HttpResponse
def export_xls(modeladmin, request, queryset):
meta = modeladmin.model._meta
filename = '%s.xls' % meta.verbose_name_plural.lower()
def get_verbose_name(fieldname):
name = filter(lambda x: x.name == fieldname, meta.fields)
if name:
return (name[0].verbose_name or name[0].name).upper()
return fieldname.upper()
response = HttpResponse(mimetype='application/ms-excel')
response['Content-Disposition'] = "attachment;filename=%s" % filename
wbk = xlwt.Workbook()
sht = wbk.add_sheet(meta.verbose_name_plural)
for j, fieldname in enumerate(modeladmin.list_display[1:]):
sht.write(0, j, get_verbose_name(fieldname))
for i, row in enumerate(queryset):
for j, fieldname in enumerate(modeladmin.list_display[1:]):
sht.write(i + 1, j, unicode(getattr(row, fieldname, '')))
wbk.save(response)
return response
var $form = $("#changelist-form");
$form.find('select[name=action]').change(function() {
$form.find('input[name=select_across]').val(+( this.value === 'export_xls' ));
if ( this.value === 'export_xls' )
$form.append('<input type="hidden" value="1" name="_selected_action">');
else
$form.find('input[name=_selected_action][type=hidden]').remove()
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment