CSV 是一种简单的数据格式,通常为电子表格软件所使用。 它主要是由一系列的表格行组成,每行中单元格之间使用逗号(CSV 是 逗号分隔数值(comma-separated values) 的缩写)隔开。例如,下面是CSV格式的“不守规矩”的飞机乘客表。
Year,Unruly Airline Passengers1995,1461996,1841997,2351998,2001999,2262000,2512001,2992002,2732003,2812004,3042005,2032006,1342007,147
备注
前面的列表包含真实数据。 这些数据来自美国 联邦航空管理局。
CSV格式尽管看起来简单,却是全球通用的。 但是不同的软件会生成和使用不同的 CSV 的变种,在使用上会有一些不便。 幸运的是, Python 使用的是标准 CSV 库, csv ,所以它更通用。
因为 csv 模块操作的是类似文件的对象,所以可以使用 HttpResponse 替换:
import csvfrom 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') response['Content-Disposition'] = 'attachment; filename=unruly.csv' # Create the CSV writer using the HttpResponse as the "file." writer = csv.writer(response) writer.writerow(['Year', 'Unruly Airline Passengers']) for (year, num) in zip(range(1995, 2006), UNRULY_PASSENGERS): writer.writerow([year, num]) return response
代码和注释可以说是很清楚,但还有一些事情需要特别注意:
在任何需要返回非 HTML 内容的时候,都需要经过以下几步: 创建一个 HttpResponse 响应对象(需要指定特殊的 MIME 类型),它它传给需要处理文件的函数,然后返回这个响应对象。
新闻热点
疑难解答
图片精选