Generic admin action to export data into excel/csv

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse, HttpResponseRedirect
from pyExcelerator import *
from django.contrib.admin.util import lookup_field
from django.utils.html import strip_tags
from django.contrib import messages


def export_as_xls(modeladmin, request, queryset):
    """
    Generic xls export admin action.
    """
    if queryset.count()>settings.EXPORT_RECORDS_LIMIT:
        messages.error(request, "Can't export more then %s Records in one go. Narrow down your criteria using filters or search" % str(settings.EXPORT_RECORDS_LIMIT))
        return HttpResponseRedirect(request.path_info)
    fields = []

    #PUT THE LIST OF FIELD NAMES YOU DON'T WANT TO EXPORT
    exclude_fields = [] 

    #foreign key related fields
    extras = ['']

    if not request.user.is_staff:
        raise PermissionDenied

    for f in modeladmin.list_display:
        if f not in exclude_fields:
            fields.append(f)
    fields.extend(extras)
    
    opts = modeladmin.model._meta

    wb = Workbook()
    ws0 = wb.add_sheet('0')
    col = 0
    field_names = []

    # write header row
    for field in fields:
        ws0.write(0, col, field)
        field_names.append(field)
        col = col + 1
    row = 1

    # Write data rows
    for obj in queryset:
        col = 0
        for field in field_names:
            if field in extras:
                try:
                    val = [eval('obj.'+field)] #eval sucks but easiest way to deal
                except :
                    val = ['None']
            else:
                try:
                    val = lookup_field(field, obj, modeladmin)
                except :
                    val = ['None']
            ws0.write(row, col, str(strip_tags(val[-1])).strip())
            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 = "Export selected to XLS"

More like this

  1. Generic csv export admin action by dek 4 years, 7 months ago
  2. Generic admin action export selected rows to excel by jordic 2 years, 6 months ago
  3. Generic CSV export admin action factory with relationship spanning fields and labels by blackrobot 1 year, 3 months ago
  4. Generic CSV export admin action factory with labels by losttrekker 2 years, 1 month ago
  5. Generic CSV export admin action factory with relationship spanning fields and labels, and many to many fields by selimnairb 2 months, 2 weeks ago

Comments

(Forgotten your password?)