django可以将数据库里面的数据生成到CSV文件里面,用户可以下载CSV文件,之后使用excle打开就可以看到
def csv1(request):
# 如果是open函数的话,必须写newline='',这个的意思是,文件输出的时候,、
# 对于特殊字符串,你写什么就是什么
with open('my.csv','w',newline='') as csvfile:
writer = csv.writer(csvfile) # 生成一个写对象
writer.writerow(['4','5','5'])
writer.writerow(['7', '8', '5'])
t = time.time()
return HttpResponse(str(t))
以上的代码就可以生成
def csvdowlod(request):
reponse = HttpResponse(content_type='text/csv')
# 添加一个响应头 attachment 附件,就是告诉浏览器,你要下载这个东西
reponse['Content-Disposition'] = 'attachment;filename = "my.csv"'
# 解决中文乱码
reponse.write(codecs.BOM_UTF8)
xw_list = jtsgb.objects.all()
writer = csv.writer(reponse)
writer.writerow(["文章名称", "作者"])
for item in xw_list:
writer.writerow([item.name, item.zzxm])
return reponse