Django - 檢視層 - 生成CSV檔案

學習中的小菜鳥.發表於2021-01-03

使用python的csv庫

import csv
from django.http import HttpResponse

def some_view(request):
	response = HttpResponse(content_type='text/csv')
	response['Content_Disposition'] = 'attachment; filename="somefilename.csv"'
	writer = csv.writer(response)
	writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
    writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])

	return response
  • 響應物件MIME型別設定為text/csv
  • 響應物件設定了附加的Content-Disposition協議頭,含有CSV檔案的名稱
  • 對於CSV檔案的每一行,呼叫writer.writerow,向它傳遞一個可迭代的物件比如列表或者元組

相關文章