Skip to content

Instantly share code, notes, and snippets.

@jtiai
Created June 6, 2013 10:36
Show Gist options
  • Save jtiai/5720647 to your computer and use it in GitHub Desktop.
Save jtiai/5720647 to your computer and use it in GitHub Desktop.
Simple sample how to export data as CSV in Excel compatible format
import csv, codecs, cStringIO
from django.template.defaultfilters import yesno
class excel_semicolon(csv.excel):
"""Describe the usual properties of Excel-generated CSV files."""
delimiter = ';'
csv.register_dialect("excel-semicolon", excel_semicolon)
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=excel_semicolon, encoding="utf-8", **kwds):
# Redirect output to a queue
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
csv.excel.delimiter
self.writer.writerow([s.encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = self.encoder.encode(data)
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
def report_csv(request):
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=netreg_report.csv'
writer = UnicodeWriter(response, encoding='windows-1252')
titles = [_('Firstname'), _('Lastname'), _('Email'), _('Phone'), _('Streetaddress'), _('Zipcode'),
_('City'), _('Area'), _('Area type'), _('Registration date'), _('Apartment type'),
_('Owner'), _('Confirmed'), _('Accepts email'), _('Requested contact'), _('Deleted')]
writer.writerow(titles)
for r in registrations:
writer.writerow([
r.firstname, r.lastname, r.email, r.phone,
r.address.netreg_address.streetname,
r.address.netreg_address.zipcode,
r.address.netreg_address.city,
(r.service_area and unicode(r.service_area)) or u'',
(r.service_area and unicode(r.service_area.category)) or u'',
r.creation_date.isoformat(sep=' '),
unicode(r.apartment_type),
yesno(r.owner),
yesno(r.confirmed),
yesno(r.send_email),
yesno(r.contact_request),
yesno(r.deleted),
])
writer.writerow([])
writer.writerow([_('Total'), unicode(registrations.count())])
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment