目录
使用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,向它传递一个可迭代的对象比如列表或者元组