在编写自动化测试用例的时候,我们常常要用到excel来管理测试数据,通常是放来一个单元格内,数据格式形式如下:
A=B;C=D
但是我们拿的时候,呈现出来的是字典形式更好些,为此我们需要用到xlrd3,还有其他的一些方法来获取。希望能对您有所帮助。
#!/user/bin/env python #coding=utf-8
import xlrd3 import json from framework.logger import Logger logger = Logger(logger="excelUtil").getlog()
class excelUtil:
def __init__(self,):
'''
初始化
什么都不做:pass
'''
pass
def getAllRowsBySheetIndex(self,sheetIndex, xlsFilePath):
'''
获取行视图
根据Sheet序号获取该Sheet包含的所有行,返回值类似[ ['a', 'b', 'c'], ['1', '2', '3'] ]
sheetIndex指示sheet的索引,0表示第一个sheet,依次类推
xlsFilePath是Excel文件的相对或者绝对路径
'''
workBook = xlrd3.open_workbook(xlsFilePath)
table = workBook.sheets()[sheetIndex]
rows = []
rowNum = table.nrows # 总共行数
rowList = table.row_values
for i in range(rowNum):
rows.append(rowList(i)) # 等价于rows.append(i, rowLists(i))
return rows
def getRow(self,sheetIndex, rowIndex, xlsFilePath):
'''
获取某个Sheet的指定序号的行
sheetIndex从0开始
rowIndex从0开始
'''
rows = self.getAllRowsBySheetIndex(sheetIndex, xlsFilePath)
return rows[rowIndex]
def getAllColsBySheetIndex(self,sheetIndex, xlsFilePath):
'''
获取列视图
根据Sheet序号获取该Sheet包含的所有列,返回值类似[ ['a', 'b', 'c'], ['1', '2', '3'] ]
sheetIndex指示sheet的索引,0表示第一个sheet,依次类推
xlsFilePath是Excel文件的相对或者绝对路径
'''
workBook = xlrd3.open_workbook(xlsFilePath)
table = workBook.sheets()[sheetIndex]
cols = []
colNum = table.ncols # 总共列数
colList = table.col_values
for i in range(colNum):
cols.append(colList(i))
return cols
def getCol(self,sheetIndex, colIndex, xlsFilePath):
'''
获取某个Sheet的指定序号的列
sheetIndex从0开始
colIndex从0开始
'''
cols = self.getAllColsBySheetIndex(sheetIndex, xlsFilePath)
return cols[colIndex]
def getCellValue(self,sheetIndex, rowIndex, colIndex, xlsFilePath):
'''
获取指定sheet的指定行列的单元格中的值
'''
workBook = xlrd3.open_workbook(xlsFilePath)
table = workBook.sheets()[sheetIndex]
return table.cell(rowIndex, colIndex).value # 或者table.row(0)[0].value或者table.col(0)[0].value
def getDict(self,sheetIndex, rowIndex, colIndex, xlsFilePath):
'''
对预置数据(返回的是string)做转换,转成字典
'''
str1 = self.getCellValue(sheetIndex, rowIndex, colIndex, xlsFilePath)
if str1.endswith(';'):
str1=str1[:-1]
rcpList = str1.split(';')
else:
rcpList = str1.split(';')
#rcpList = str1.split(';')
rcpDict = {}
for List in rcpList:
rcpDict.update(self.listTODcit(List.split('=')))
logger.info('测试数据为:%s' % rcpDict)
return rcpDict
def listTODcit(self,List):
'''
把列表转换成字典
'''
return ({List[0].strip() : List[1].strip()})
''' 工具的调用示例 ''' if name=='main': ex = excelUtil() ex.getDict(4, 2, 4, r'E:\autoTest\rcpAutoTest_20190920\test_data\rcpAutoTest.xls')