本站停止维护,已转移至laravel学习网;欢迎大家移步访问!

python 操作excel以及解决中文报错

xlwt,xlrd是python读写操作excel的模块,下载xlrd:http://pypi.python.org/pypi/xlrd 下载xlwt:http://pypi.python.org/pypi/xlwt    下载后安装即可

sudo python setup.py intall

那么我们怎么读写excel呢?怎么解决中文报错呢?我这里总结了所有方法,大家直接运行就可以了,有注释

# -*- coding: utf-8 -*-
import xlwt
import xlrd
import sys
reload(sys)
sys.setdefaultencoding('utf8')

class Excel(object):
    """套号"""
    def __init__(self, usename,password):
        self.usename = usename
        self.password = password

    # 设置表头
    def WriteSheetRow(self,sheet,rowValueList,rowIndex,isBold):
        i = 0
        style = xlwt.easyxf('font: bold 1')
        #style = xlwt.easyxf('font: bold 0, color red;')#红色字体
        #style2 = xlwt.easyxf('pattern: pattern solid, fore_colour yellow; font: bold on;') # 设置Excel单元格的背景色为黄色,字体为粗体
        for svalue in rowValueList:
            strValue = unicode(str(svalue),'utf-8')
            if isBold:
                sheet.write(rowIndex,i,strValue,style)
            else:
                sheet.write(rowIndex,i,strValue)
            i = i + 1

    # 写入excel
    def write(self):
        wb = xlwt.Workbook()
        # 表名
        ws = wb.add_sheet('setno')
        headList = ['ID','电话','姓名']
        rowIndex = 0
        self.WriteSheetRow(ws,headList,rowIndex,True)
        # ws.write(0, 0, 1234.56, style0)
        # ws.write(1, 0, datetime.now(), style1)
        ws.write(1, 0, "1")
        ws.write(1, 1, "15512342222")
        ws.write(1, 2, "李雷".decode('utf-8'))
        ws.write(2, 0, "2")
        ws.write(2, 1, "15512342222")
        ws.write(2, 2, "韩梅梅".decode('utf-8'))
        wb.save('setno.xlsx')

    def read(self):
        data = xlrd.open_workbook("setno.xlsx")
        table = data.sheets()[0]
        nrows = table.nrows #行数
        ncols = table.ncols #列数
        for i in xrange(0,nrows):
            rowValues= table.row_values(i) #某一行数据
            for item in rowValues:
                print item

if __name__ == "__main__":
    excel = Excel("1","2")
    excel.write()
转载请注明 :一沙网络原文出处:http://bbs.earnp.com/article/307
问题交流群 :562864481
0
打赏
发布时间 :2016-12-29 20:10:25
分享

0 个评论

    还没有评论,感觉来抢沙发吧!

要回复文章请先登录注册