1.在django views.py中使用HttpResponse
views.py首行加上utf-8編碼,將默認unicode編碼變為utf-8
1 # -*- coding:utf-8 -*-
下面是利用HttpResponse生成csv文件
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編碼。
2.在url.py中配置views中方法的url路徑
1 url(r'^download/csv', views.download_csv, name='dowmload_csv') #分別為路徑名、方法名
3.方法一 在html中直接鏈接到該url實現下載
1 <button type="button" 2 onclick="location.href='download/csv'"> 3 下載 4 </button>
4.方法二 在js中實現下載
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得到傳來的值
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方法即可實現文件下載