views.py首行加上utf-8编码,将默认unicode编码变为utf-8php
1 # -*- coding:utf-8 -*-
下面是利用HttpResponse生成csv文件html
1 response = HttpResponse(content_type='text/csv;charset=UTF-8') 2 response.write(codecs.BOM_UTF8) #加入BOM头才能在csv文件中添加中文,不然在excel中是乱码,此句必须加在下句的前面,否则没做用 3 response['Content-Disposition'] = 'attachment; filename="systemInteriorLog.csv"' 4 5 writer = csv.writer(response) 6 writer.writerow(['时间', '日志ID', '动做', '状态', '类型', '内容'])
从数据库中提取的数据中的中文能够用encode()方法编码,以下:数据库
1 writer.writerow([ log.type.encode('utf-8'), log.description.encode('utf-8')])
这里再说一下decode和encode方法的做用:
decode()将其余编码转换为unicode编码,如decode('gb2313')是将gb2312编码的字符串转为unicode编码;
encode()将unicode编码转换为其余编码,如encode('gb2312')是将unicode编码的字符串转为gb2312编码。django
1 url(r'^download/csv', views.download_csv, name='dowmload_csv') #分别为路径名、方法名
1 <button type="button" 2 onclick="location.href='download/csv'"> 3 下载 4 </button>
1 window.location.href='download/csv';
1 var url = "www.xxx.com/index.php"; 2 window.location.href = url + "?a=1&b=2"; 3 //使用location.herf还能够实现向views中的request传值 4 window.location.href='/download/interior/csv'+ '?a='+$scope.a+'&b='+$scope.b;
在views方法中能够用GET获得传来的值ui
1 @http_method_required('GET') 2 def get_interior_csv(request): 3 get_a = request.GET.get('a') 4 get_b = request.GET.get('b')
以后再在html文件中调用所写的js方法便可实现文件下载编码