django 生成csv文件重要代码

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 替换

 

posted @ 2016-04-17 16:48  Xiao|Deng  阅读(516)  评论(0编辑  收藏  举报