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 類型),它它傳給需要處理文件的函數,然后返回這個響應對象。
新聞熱點
疑難解答
圖片精選