Login

Generic admin action export selected rows to excel

Author:
jordic
Posted:
September 30, 2011
Language:
Python
Version:
1.3
Tags:
export admin-actions xls
Score:
2 (after 2 ratings)

Based on http://djangosnippets.org/snippets/1697/ but improved with multiline fields, and unicode chars. Also it generates an xls file, not a csv one.

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


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
    
    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_csv.short_description = "Export selected objects to XLS"

More like this

  1. Generic admin action export selected rows to excel by aemb87 2 years, 4 months ago
  2. Admin action for a "CSV Export" with ManyToManyField by CarlosRodriguez 8 months, 1 week ago
  3. Generic csv export admin action by dek 5 years, 6 months ago
  4. Ultimate(?) export/download CSV admin action by anentropic 1 year, 4 months ago
  5. Admin action for a generic "CSV Export" by javinievas 4 years ago

Comments

aemb87 (on October 19, 2012):

Hi! this is awesome, i've just used it for one of my projects.

I did a small change so i dont have to save it to the filesystem:

f = StringIO()
wb.save(f)
f.seek(0)
response = HttpResponse(f.read(), mimetype='application/ms-excel')

I hope this can be helpful to somebody!

Andrés

#

Please login first before commenting.