开发者社区> 问答> 正文

python 保存 excel文件时报错:报错

我的参考网上别人的代码的,在我本机子上(win7)都可以

到了公司的服务器上(djingo/linux) 就报错 提示在  save的时候报:

'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)

代码如下:  ( 我本机和公司机器上的主要代码相同, 就是 保存的路径完全不同!!!)

                         公司路径打印出来:/项目名/xx/xxx/info.xls(名子表示个意思,实际全英文)

class Try:
    def xls():
        #xls info
        wbk=xlwt.Workbook()
        sheet=wbk.add_sheet('sheet 1')
        #connect Info
        try:
           
            conn = MySQLdb.connect('localhost','root','ok','smyw_edit_server')
            cursor = conn.cursor()
            sql='select * from ser_user'
           
            #获取要打印的列名
            columnName=[u'编号',u'用户名',u'密码',u'注册时间',u'最后一次登录时间',u'是否启用']
            #获取列数
            columnLen=len(columnName)
            #打印出标题
            for i in range(columnLen):
                    sheet.write(0,i,columnName[i])
           
            #执行sql       
            cursor.execute(sql)
            #获取到查询得到的数据
            dataInfo=cursor.fetchall()
            dataLen = len(dataInfo)
            rowLine=0
            #排个顺序
            for line in range(dataLen):
                    lineInfo=dataInfo[line]
                    rowLine+=1
                    columnLine=0
                    #print line
                    #按每行打印
                    for row in lineInfo:
                            if type(row)==str:
                                row=row.encode('utf-8')
                                #print row
                            sheet.write(rowLine,columnLine,row)
                            columnLine+=1
           
            #print table
            #保存打印的excel数据
            wbk.save('c:%s.xls' % 'info')
            #print xlwt.Workbook()
            #打开打印的excel数据
           
            cursor.close()
            conn.commit()
            conn.close()
            sys.exit(1)
        except Exception,e:
            print e
        finally :
            print 'over!'
    if __name__=='__main__':
            xls()

 

展开
收起
kun坤 2020-06-14 11:22:13 959 0
1 条回答
写回答
取消 提交回答
  • 从报错信息来看,是字符集编码的错误,试试将sheet.write(0,1,column[i])改为sheet.write(0,1,column[i].encode('utf-8)),原因是python的内置编码是默认ascii的,而你的代码中出现了中文,因此会报错,如果上面的改法还报错,请尝试在程序开头添加如下代码:

    import sys 

    reload(sys)

    sys.setdefaultencoding('utf-8')



    2020-06-14 11:22:18
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载