Created
January 4, 2012 14:20
-
-
Save snahor/1560240 to your computer and use it in GitHub Desktop.
Django admin export all the records of the current queryset to XLS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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