zoukankan      html  css  js  c++  java
  • 写excel 报错UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in rang

    C:Python27python.exe C:/Users/Administrator/PycharmProjects/untitled/a3.py
    Traceback (most recent call last):
      File "C:/Users/Administrator/PycharmProjects/untitled/a3.py", line 83, in <module>
        write_data_to_excel(k, v)
      File "C:/Users/Administrator/PycharmProjects/untitled/a3.py", line 49, in write_data_to_excel
        wbk.save(name + str(today_date) + '.xls')
      File "C:Python27libsite-packagesxlwtWorkbook.py", line 710, in save
        doc.save(filename_or_stream, self.get_biff_data())
      File "C:Python27libsite-packagesxlwtWorkbook.py", line 674, in get_biff_data
        shared_str_table   = self.__sst_rec()
      File "C:Python27libsite-packagesxlwtWorkbook.py", line 636, in __sst_rec
        return self.__sst.get_biff_record()
      File "C:Python27libsite-packagesxlwtBIFFRecords.py", line 77, in get_biff_record
        self._add_to_sst(s)
      File "C:Python27libsite-packagesxlwtBIFFRecords.py", line 92, in _add_to_sst
        u_str = upack2(s, self.encoding)
      File "C:Python27libsite-packagesxlwtUnicodeUtils.py", line 50, in upack2
        us = unicode(s, encoding)
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)

    Process finished with exit code 1


    # !/usr/bin/env python
    # -*- coding: utf-8 -*-
    import MySQLdb
    from datetime import datetime
    import  cx_Oracle
    import os
    import xlwt
    import sys
    reload(sys)
    sys.setdefaultencoding('utf-8')
    os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'


    def get_data(sql):
        # 创建数据库连接.
        conn = cx_Oracle.connect('')#. 创建游标
        cur = conn.cursor()
        # 执行查询,
        cur.execute(sql)
        # 由于查询语句仅会返回受影响的记录条数并不会返回数据库中实际的值,所以此处需要fetchall()来获取所有内容。
        result = cur.fetchall()
        # 关闭游标
        cur.close()
        # 关闭数据库连接
        conn.close
        # 返给结果给函数调用者。
        print result
        return result


    def write_data_to_excel(name, sql):
        # 将sql作为参数传递调用get_data并将结果赋值给result,(result为一个嵌套元组)
        result = get_data(sql)
        # 实例化一个Workbook()对象(即excel文件)
        wbk = xlwt.Workbook(encoding='utf-8')
        # 新建一个名为Sheet1的excel sheet。此处的cell_overwrite_ok =True是为了能对同一个单元格重复操作。
        sheet = wbk.add_sheet('Sheet1', cell_overwrite_ok=True)
        # 获取当前日期,得到一个datetime对象如:(2016, 8, 9, 23, 12, 23, 424000)
        today = datetime.today()
        # 将获取到的datetime对象仅取日期如:2016-8-9
        today_date = datetime.date(today)
        # 遍历result中的没个元素。
        for i in xrange(len(result)):
            # 对result的每个子元素作遍历,
            for j in xrange(len(result[i])):
                # 将每一行的每个元素按行号i,列号j,写入到excel中。
                sheet.write(i, j, result[i][j])
        # 以传递的name+当前日期作为excel名称保存。
        wbk.save(name + str(today_date) + '.xls')


    # 如果该文件不是被import,则执行下面代码。
    if __name__ == '__main__':
        mysql="select to_char(t.trans_date,'yyyy-mm-dd Hh24:mm:ss') as 交易日期,t.esbserviceflowno as 全局流水号,t.serviceid as 服务场景码, s.description  as 服务场景码描述
      from esb2_trans_log t,serviceinfo s
     where t.trans_date >=
           to_date('2018-06-07 00:00:00', 'yyyy-mm-dd hh24:mi:ss')
       and t.trans_date <=
           to_date('2018-06-07 23:59:59', 'yyyy-mm-dd hh24:mi:ss')
       /*and t.logicsystem = 'LOAN'*/
       and t.serviceid=s.serviceid
       and (t.respmsg like '%Read timed out%' or t.respmsg like '%异常%' or
           t.respmsg like '%超时%')
       and t.esbserviceflowno is not null  
       and t.respcode<>'000000'
          and  (t.logicsystem<>'AAAA' or t.respmsg <>'TGT已超时')
       AND  (t.logicsystem<>'ELINK' or t.respcode<>'3040')
       AND  (t.logicsystem<>'IBPS' or t.respcode<>'600011')
       AND (t.logicsystem<>'CNAPS' or t.respcode<>'AHVB001')
       AND (t.logicsystem<>'CNAPS' or t.respcode<>'UPC002')
       AND  (t.logicsystem<>'CNAPS' or t.respcode<>'UPC002')
       AND  (t.logicsystem<>'ELINK' or t.respcode<>'Y999')
       and (t.logicsystem<>'ELINK' or t.respcode<>'600011')
        and (t.logicsystem<>'CIPS' or t.respcode<>'500101092209')
        and (t.logicsystem<>'CCFS' or t.respcode<>'500101092209')
       and (t.logicsystem<>'ELINK' or t.respcode<>'0201')
       "
        # 定义一个字典,key为对应的数据类型也用作excel命名,value为查询语句
        title='ESB日报'
        title=title.decode('utf-8').encode('gbk')
        db_dict = {title: mysql}
        # 遍历字典每个元素的key和value。
        for k, v in db_dict.items():
            # 用字典的每个key和value调用write_data_to_excel函数。
            write_data_to_excel(k, v)



     wbk = xlwt.Workbook(encoding='utf-8')   没有指定为utf-8报错 

    UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)
  • 相关阅读:
    第四章例4-5
    第四章例4-4
    修改oracle 客户端PL/SQL 的路径问题
    解决div float后,父div高度无法自适应的问题
    include与jsp:include与s:action与s:include与iframe用法汇总
    解决js中onMouseOut事件冒泡的问题
    strut2配置action class 问题
    html块级元素与行内元素
    Tomcat 启动不了的问题
    oracle远程导入导出
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13349186.html
Copyright © 2011-2022 走看看