首页 > 其他 > 详细

django 生成csv文件

时间:2016-04-17 17:48:28      阅读:193      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!