码迷,mamicode.com
首页 > 其他好文 > 详细

D-django自定义导出csv文件

时间:2017-11-28 15:31:02      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:djang   created   type   ade   name   header   csv   iter   tac   

import csv
from datetime import timedelta

def download_csv(commend=None):
    response = HttpResponse(content_type=text/csv)
    response[Content-Disposition] = attachment;filename=download.csv
    response.write(\xEF\xBB\xBF)
    
    writer = csv.writer(response)
    headers = [u"姓名",u"年龄",u"性别"]
    headers = [item.encode(utf8) for item in headers]
    writer.writerow(headers)
  list_user = User.object.filter(**commend).order_by("-datetime_created")
  queryset = list_user.values_list("user__username","age","sex")
  for idx,row in enumerate(queryset):
    values = []
    cnt = 0
    for field in row:
        cnt += 1
        value = ‘‘
      if cnt == 2:
        if int(field) == 0:
          value = u
        elif int(field) == 1:
          value = u
      elif field:
          if type(field) is datetime.datetime or type(field) is datetime.date:
              field = field + timedelta(hours=8)
              value = field.strftime("%Y-%m-%d")
          else:
              value = field 
       values.append(unicode(value).encode(utf-8))
    writer.writerow(values)
  return response

 

D-django自定义导出csv文件

标签:djang   created   type   ade   name   header   csv   iter   tac   

原文地址:http://www.cnblogs.com/bk770466199/p/7909790.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!