Created
April 4, 2012 23:02
-
-
Save ajamaica/2306404 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
from django.core.exceptions import PermissionDenied | |
from django.http import HttpResponse | |
from pyExcelerator import * | |
def export_as_xls(modeladmin, request, queryset): | |
""" | |
Exporta XLS totalmente generico | |
Requiere pyExcelerator | |
Para usar agrega actions = [export_as_xls] | |
""" | |
if not request.user.is_staff: | |
raise PermissionDenied | |
opts = modeladmin.model._meta | |
wb = Workbook() | |
ws0 = wb.add_sheet('0') | |
col = 0 | |
field_names = [] | |
# Cabezeras | |
for field in opts.fields: | |
ws0.write(0, col, field.name) | |
field_names.append(field.name) | |
col = col + 1 | |
row = 1 | |
# Filas | |
for obj in queryset: | |
col = 0 | |
for field in field_names: | |
val = unicode(getattr(obj, field)).strip() | |
ws0.write(row, col, val) | |
col = col + 1 | |
row = row + 1 | |
wb.save('/tmp/output.xls') | |
response = HttpResponse(open('/tmp/output.xls','r').read(), | |
mimetype='application/ms-excel') | |
response['Content-Disposition'] = 'attachment; filename=%s.xls' % unicode(opts).replace('.', '_') | |
return response | |
export_as_xls.short_description = "Exporta a XLS" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment