Login

Generic admin action export selected rows to excel

Author:
aemb87
Posted:
October 19, 2012
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

Based on Snippet 2558 but without saving the generated file to disk before downloading.

Requires, pyExcelerator

Usage:

Add the code to your project, e.g. a file called actions.py in the project root.

Register the action in your apps admin.py:

from myproject.actions import export_as_xls class MyAdmin(admin.ModelAdmin): actions = [export_as_xls]

 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
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from pyExcelerator import *
from StringIO import StringIO


def export_as_xls(modeladmin, request, queryset):
    """
    Generic xls export admin action.
    """
    if not request.user.is_staff:
        raise PermissionDenied
    opts = modeladmin.model._meta
    
    wb = Workbook()
    ws0 = wb.add_sheet('0')
    col = 0
    field_names = []
    # write header row
    for field in opts.fields:
        ws0.write(0, col, field.name)
        field_names.append(field.name)
        col = col + 1
    
    row = 1
    # Write data rows
    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	

	f = StringIO()
	wb.save(f)
	f.seek(0)
	response = HttpResponse(f.read(), mimetype='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename=%s.xls' % unicode(opts).replace('.', '_')
    return response
    
export_as_xls.short_description = "Export selected objects to XLS"

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.