11-Python操作excel

1python操作excel需要用到的库

python操作excel主要用到xlrd和xlwt这两个库,即xlrd是读excel,xlwt是写excel的库可以直接pip安装这两个库,pip install xlrd 、pip install xlwt

2、python封装常用读取excel方法

# coding:utf-8
import xlrd
import sys

# 解决Unicode equal comparison failed to convert both arguments to Unicode - interpreting问题
# uncode编码警告:在unicode等价比较中,把两个参数同时转换为unicode编码失败。中断并认为他们不相等
# windows下的字符串str默认编码是ascii,而python编码是utf8
reload(sys)
sys.setdefaultencoding('utf8')


class OperExcel:
    def __init__(self, filename=None, sheet_id=None):
        if filename:
            self.filename = filename
            self.sheet_id = sheet_id
        else:
            self.filename = '../dataconfig/test.xlsx'
            self.sheet_id = 0
        self.data = self.get_dataBySheetId()

    # 根据sheetid获取sheet内容
    def get_dataBySheetId(self):
        data = xlrd.open_workbook(self.filename)
        tables = data.sheets()[self.sheet_id]
        return tables

    # 根据sheet名称获取sheet内容
    def get_dataBySheetName(self,filepath,sheetname):
        data = xlrd.open_workbook(filepath)
        tables = data.sheet_by_name(sheetname)
        return tables

    # 获取sheet表行数
    def get_lines(self):
        tables = self.data
        return tables.nrows

    # 根据行列值获取单元格内容
    def get_cell_value(self, row, col):
        tables = self.data
        return tables.cell_value(row, col)

    # 根据列头名称,获取所在列Index
    def get_columnindex(self, colName):
        tables = self.data
        columnIndex = None
        for i in range(tables.ncols):
            if (tables.cell_value(0, i) == colName):
                columnIndex = i
                break
        return columnIndex

    def get_rowIndex_ByColIndexAndValue(self,colIndex,cellValue):
        tables = self.data
        rowIndex = None
        for i in range (tables.nrows):
            if (tables.cell_value(i,colIndex) == cellValue):
                roeIndex = i
                break;
        return i


if __name__ == '__main__':
    oper = OperExcel()
    print oper.get_lines()
    print oper.get_cell_value(1, 1)
    print oper.get_columnindex('密码')
    print oper.get_rowIndex_ByColIndexAndValue(1,'ww123456')
    print oper.get_dataBySheetName('../dataconfig/test.xlsx','Sheet1').cell_value(1,1)

猜你喜欢

转载自www.cnblogs.com/santiandayu/p/10017547.html
今日推荐