这两个是基础函数
from django.utils.encoding import smart_str
def join_line(line):
tmpl = ','.join([u'"{}"'] * len(line))
return smart_str(tmpl.format(*line))
def response_csv(title, lines, encoding='utf-8'):
from django import http
import codecs
if isinstance(title, unicode):
title = title.encode(encoding)
response = http.HttpResponse(codecs.BOM_UTF8 + ('\r\n'.join(lines)), content_type='text/csv')
response['Content-Disposition'] = 'attachment;filename="{}.csv"'.format(title)
return response
引用
def make_lines_day_all(values):
lines = []
for v in values:
date = v.get('date')
print date
register_num = v.get('register_num')
income = '{:.2f}'.format(v.get('income') * 0.01)
join_num = v.get('join_num')
visit_num = v.get('visit_num')
line = [date, register_num, income, visit_num, join_num]
lines.append(join_line(line))
return lines
def export_day_all(request):
query = BizStatistics.objects.values().all()
print query
title = '商家每日总数据报表'
lines = [join_line((u'日期', u'注册量', u'收入', u'浏览量', u'客资'))]
lines += make_lines_day_all(query)
return response_csv(title, lines)