• Django 导出csv文件 中文乱码问题


    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文件,中文显示正常,如图。

     这样改的原理:

    .....

  • 相关阅读:
    Selct 大全
    Web API
    其他
    ADO.NET Entity Framework
    ORACLE SQL前端补0的三种方式。
    linux常用命令
    oracle 创建修改 job
    oracle 如何恢复误删的表记录数据
    myeclipse上SVN代码合并详细步骤图解
    SVN创建资源与分支详解
  • 原文地址:https://www.cnblogs.com/haoshine/p/5695760.html
Copyright © 2020-2023  润新知