写excel 报错UnicodeDecodeError: ‘ascii‘ codec can‘t decode byte 0xe5 in position 0: ordinal not in rang

C:\Python27\python.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:\Python27\lib\site-packages\xlwt\Workbook.py", line 710, in save
    doc.save(filename_or_stream, self.get_biff_data())
  File "C:\Python27\lib\site-packages\xlwt\Workbook.py", line 674, in get_biff_data
    shared_str_table   = self.__sst_rec()
  File "C:\Python27\lib\site-packages\xlwt\Workbook.py", line 636, in __sst_rec
    return self.__sst.get_biff_record()
  File "C:\Python27\lib\site-packages\xlwt\BIFFRecords.py", line 77, in get_biff_record
    self._add_to_sst(s)
  File "C:\Python27\lib\site-packages\xlwt\BIFFRecords.py", line 92, in _add_to_sst
    u_str = upack2(s, self.encoding)
  File "C:\Python27\lib\site-packages\xlwt\UnicodeUtils.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)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

scan724

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值