import csv
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
def export_as_csv(modeladmin, request, queryset):
"""
Generic csv export admin action.
"""
if not request.user.is_staff:
raise PermissionDenied
opts = modeladmin.model._meta
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=%s.csv' % unicode(opts).replace('.', '_')
writer = csv.writer(response)
field_names = [field.name for field in opts.fields]
# Write a first row with header information
writer.writerow(field_names)
# Write data rows
for obj in queryset:
writer.writerow([getattr(obj, field) for field in field_names])
return response
export_as_csv.short_description = "Export selected objects as csv file"
Comments
This generates the error "'ascii' codec can't encode characters in position ...". How can this be extended to handle UTF-8 encoding?
#
Combined dek's idea with a snippet from Anatoly Ivanov.
Works, with german ÄÖÜ and TextFields, Excel 2003+ compatible:
http://weitlandt.com/theme/2010/05/wir-djangonauten-csv-export-nach-excel-mit-umlauten/
#
Combined dek's idea with a snippet from Anatoly Ivanov.
Solved, with german ÄÖÜ and TextFields, Excel 2003+ compatible:
http://weitlandt.com/theme/2010/05/wir-djangonauten-csv-export-nach-excel-mit-umlauten/
#
thanks!
a slightly customised version: #2020
#