轉載請註明出處:http://www.javashuo.com/article/p-zbvwbcrc-bo.htmlhtml
前提:自動化接口測試中,能夠將用例放在excel中管理。結合實際狀況講解如何操做excel文件測試
1.安裝xlrd:pip install xlrdspa
2.導入模塊:import xlrdexcel
3.打開Excel文件讀取數據code
data = xlrd.open_workbook('../dataconfig/interface.xlsx')
4.獲取一個工做表(兩種方式均可以)htm
table = data.sheets()[0] #經過索引順序獲取
table = data.sheet_by_index(0) #經過索引順序獲取
5.獲取表名稱blog
name = table.name
6.獲取行數和列數索引
nrows = table.nrows nclos = table.ncols
7.獲取某行和某列的值接口
row_value= table.row_values(i) col_value = table.col_values(i)
8.循環 行/列 的數據ip
for i in range(nrows): print(table.row_values(i)) for j in range(nclol): print(table.col_values(j))
9.獲取單元格數據(兩種方式)
cellvalue = table.cell(row,col).value cellvalue = table.cell_value(row,col)
代碼參考:將相關方法進行封裝,使用過程能夠直接調用
1 #coding:utf-8
2 import xlrd 3
4 class OperationExcel: 5 def __init__(self,file_name=None,sheet_id=None): 6 if file_name: 7 self.file_name = file_name 8 self.sheet_id = sheet_id 9 else: 10 self.file_name = '../dataconfig/interface.xlsx'
11 self.sheet_id = 0 12 self.data = self.get_data() 13
14 #獲取sheets的內容
15 def get_data(self): 16 data = xlrd.open_workbook(self.file_name) 17 tables = data.sheets()[self.sheet_id] 18 return tables 19
20 #獲取單元格的行數
21 def get_lines(self): 22 tables = self.data 23 return tables.nrows 24
25 #獲取某一個單元格的內容
26 def get_cell_value(self,row,col): 27 tables = self.data 28 cell = tables.cell_value(row,col) 29 return cell 30
31 if __name__ == '__main__': 32 opexcel = OperationExcel() 33 print(opexcel.get_cell_value(1,2))