• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
😊三天打鱼😊
博客园    首页    新随笔    联系   管理    订阅  订阅

11-Python操作excel

1、python操作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

  # 根据列Index和单元格值获取所在行
    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)

 

posted @ 2018-11-25 21:36  😊三天打鱼😊  阅读(261)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3