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

django 生成csv文件

时间:2016-04-17 17:49:18      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

import csv
from django.http import HttpResponse

# Number of unruly passengers each year 1995 - 2005. In a real application
# this would likely come from a database or some other back-end data store.
UNRULY_PASSENGERS = [146,184,235,200,226,251,299,273,281,304,203]

def unruly_passengers_csv(request):
# Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(mimetype=text/csv) #告诉浏览器,返回的文档是CSV文件 response[Content-Disposition] = attachment; filename=unruly.csv‘ #响应会有一个附加的 Content-Disposition 头部,它包含有CSV文件的文件名 # Create the CSV writer using the HttpResponse as the "file." writer = csv.writer(response) writer.writerow([Year, Unruly Airline Passengers]) #调用 writer.writerow ,并且传递给它一个类似 list 或者 tuple 的可迭代对象,就可以在 CSV 文件中写入一行 for (year, num) in zip(range(1995, 2006), UNRULY_PASSENGERS): writer.writerow([year, num]) return response

 

csv 模块操作的是类似文件的对象,所以可以使用 HttpResponse 替换

 

django 生成csv文件

标签:

原文地址:http://www.cnblogs.com/dengyg200891/p/5401385.html

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