django 生成csv文件重要代码

本文介绍如何在Django应用中将数据转换为CSV格式并进行响应,通过实例展示从数据列表到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 替换

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值