您的位置:首页 > 编程语言

django 生成csv文件重要代码

2016-04-17 16:48 351 查看
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 替换
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: