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方法便可實現文件下載編碼