2013年12月30日 星期一

[Django] Export CSV file ( 匯出CSV檔案 )

Export data to a CSV file with Django

前言:
單純因為會用到,所以就剛好寫到這個功能

想說,以後可能在別的公司or自己的server會用到,就順便整理一份範例。

Example Code:
https://gist.github.com/kilfu0701/7332112
# 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


其他參考資料:
1. CSV匯出的時候,會遇到excel格式自動判斷錯誤的問題,後來在下面這篇看到解法:
http://stackoverflow.com/questions/165042/stop-excel-from-automatically-converting-certain-text-values-to-dates

2. 官方文件
https://docs.djangoproject.com/en/dev/howto/outputting-csv/

沒有留言:

張貼留言