python 读取excel内容为中文的处理

来源:互联网 发布:mac pro 需要的配件 编辑:程序博客网 时间:2024/06/01 09:18

地址1:https://my.oschina.net/CeShiXiaoSongShu/blog/346366

地址2:http://www.cnblogs.com/blueel/archive/2012/08/21/2649590.html

地址3:http://www.cnblogs.com/work115/p/5924446.html

使用python读取excel内容并把内容写人文件时遇到问题


读取excel的内容,当excel的内容有中文时,输出为Unicode编码格式,当把数据unicode化后,输出为乱码

错误信息:

'utf8' codec can't decode byte 0xe5 in position 0: unexpected end of data


dome:

read_excel.py

# !/usr/bin/env python# -*- coding: utf-8 -*-import xlrdfrom commonality import loggimport oslog = logg.log_config()o_path = os.getcwd().encode('utf-8')# 获取excel中的数据def excel_data(files, index=0):    # 读取配置文件base下的excel_name值    # files = read_config.get_pmt('base', excel_name)    # 定义excel所有的数据excel_list    excel_list = []    if files != '':        try:            # 打开Excel文件读取数据            data = xlrd.open_workbook(files)            # 获取第一个工作表            table = data.sheet_by_index(index)            # 获取行数            nrows = table.nrows            # 获取列数            ncols = table.ncols            for row in range(1, nrows):                # 定义每行excel_rows                excel_rows = []                for col in range(ncols):                    # 获取单元格数据                    cell_value = table.cell(row, col).value                    # 把数据追加到excel_rows中                    excel_rows.append(cell_value.encode('UTF-8'))                # 把数据追加到excel_list中                excel_list.append(excel_rows)                # return excel_list            log.info('获取'+files+'文件中的数据成功。')        except Exception, e:            log.error(e)    else:        log.info(u'excel数据获取失败,excel目录为空')    return excel_list

对获取到的数据进行处理

dome2:
megan_excel.py

import sysreload(sys)# 设定了输出的环境为utf8sys.setdefaultencoding('utf-8')# 读取的excel文件路径files = 'login.xls'# 调用读取方法excel_data = read_excel.excel_data(files)pmt = []if len(excel_data[0]) > 0:    for i in range(len(excel_data[0])):        pmt = excel_data[0][i]        for j in range(len(pmt)):            # 对字符串进行unicode化            pmt[j] = unicode(pmt[j], errors='ignore')print pmt



原创粉丝点击