import csv
import codecs
import datetime
from django.db import connection
from django.contrib.auth.models import User
from django.http import HttpResponse
from models import *
def output(request, user_id, node_id, function_id): function_id = int(function_id) user_id = int(user_id) node_id= int(node_id) # 指定csv请求回应 response = HttpResponse(content_type='text/csv') user = User.objects.get(id=user_id) functions_has_permission = DataPermission.objects.filter(category=node_id) # 取出sql语句 function_obj = DataPermission.objects.get(id=function_id) function_obj_sql = function_obj.sql # 执行sql语句,并执行。保存执行结果和字段名 cursor = connection.cursor() cursor.execute(function_obj_sql) results = cursor.fetchall() descriptions = cursor.description descriptions_long = len(descriptions) description_list = [None] * descriptions_long i = 0 for description in descriptions: description_list[i] = description[0] i = i + 1 # 将执行结果从元组形式转化为列表形式。 i=0 results_long = len(results) results_list = [None] * results_long for i in range(results_long): results_list[i] = list(results[i]) # print(results_list) # 为文件取名字 now = datetime.datetime.now() now = str(now.isoformat()) name = (now + '.csv').replace(':', '') # 声明一个csv的响应 response['Content-Disposition'] = 'attachment; filename="%s"' % name # csv的响应的编码格式声明 response.write(codecs.BOM_UTF8) writer = csv.writer(response) # 转码问题 a = u'中' for result in results_list: i=0 for item in result: if type(item) == type(a): # 如果是unicode类型,那么编码成utf-8 result[i] = item.encode('utf-8') i = i + 1 # with open(response, 'wb') as f: writer.writerow(description_list) for result in results_list: writer.writerow(result) i = i + 1 response.close() return response
以上代码,导出的文件,中文显示成乱码,如图。
解决方法:将上面代码中的'utf-8' 改成 'gb2312'
result[i] = item.encode('gb2312')
修改之后,导出的csv文件,中文显示正常,如图。
这样改的原理:
.....