11-Python操作excel
阿新 • • 發佈:2018-11-25
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 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)