xlrd3讀excel的簡單實踐

在編寫自動化測試用例的時候,我們常常要用到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')

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章