Skip to content

Instantly share code, notes, and snippets.

@kilfu0701
Last active December 27, 2015 13:19
Show Gist options
  • Save kilfu0701/7332112 to your computer and use it in GitHub Desktop.
Save kilfu0701/7332112 to your computer and use it in GitHub Desktop.
Use django to export a CSV file.
# in some views.py, to serve a csv file in Django.
# -*- coding: utf-8 -*-
import csv
from django.http import HttpResponse
def donwload_csv(request):
# change export csv formatting by request parameter. ( url?encode=utf-8 )
encode = request.GET.get('encode', 'big5')
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="light_member.csv"'
writer = csv.writer(response, delimiter=',', quotechar='"')
header = [u'活動名稱', u'姓名', u'Email', u'會員身分', u'答案', u'活動登入日期', u'註冊日期', u'Device']
writer.writerow([x.encode(encode) for x in header])
# force export column by text format.
# http://stackoverflow.com/questions/165042/stop-excel-from-automatically-converting-certain-text-values-to-dates
deli = u'="{0}"'
## result['data'], some data from databases.
#result = {}
#result['data'] = list(aModel.objects.filter(**ftr).values(*fds))
for i in result['data']:
role = u'New' if i['new'] == 1 else u'Exist'
raw_row = [i['plan'], i['name'], i['email'], role, i['option'], str(i['timestamp']), str(i['joined_at']), i['os']]
row = [deli.format(x).encode(encode) for x in raw_row ]
writer.writerow(row)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment