selenium 数据驱动框架自动化从0到1–7
上一篇我们做了数据源的设计与配置,这一篇我们就来说一下解析excel 文件的方法封装
在util 包下新建一个excel_parse.py 文件用来实现解析excel 文件的方法封装,作为一个工具类可直接使用,代码如下:
#encoding=utf-8
from openpyxl import load_workbook
from openpyxl.styles import Font, PatternFill #字体颜色和背景
import time
import locale
class ExcelParse(object):
def __init__(self,excelFilePath):
self.wb = None
self.filePath = excelFilePath
self.ft = Font(color=None) # 初始化字体颜色
self.locale = locale.setlocale(locale.LC_CTYPE, 'chinese') #设置中文时间格式
self.pf = PatternFill(fill_type='solid', fgColor='FFFFFF') #初始化背景颜色
self.RGBDict = {'red': 'FF0000', 'green': '00FF00',
'yellow': 'FFD700', 'blue':'33A1C9', 'black': '000000'} #颜色数据
def load_workbook(self): #加载已存在的excel文件,返回一个文件对象
try:
self.wb = load_workbook(self.filePath) #加载文件
except Exception as e:
raise e
return self.wb
def save(self): #保存文件
self.wb.save(self.filePath)
def create_sheet(self,sheetName,position=None) -> bool:
# 在指定位置创建一个sheet,创建成功返回True,创建失败返回False
try:
if position:
self.wb.create_sheet(sheetName, position)
else:
self.wb.create_sheet(sheetName)
self.save()
return True
except Exception as e:
print(e)
return False
def get_all_sheet_name(self): #获取所有sheet 名字
return self.wb.sheetnames
def get_sheet_by_name(self, sheetName): #通过sheet名获取sheet 对象
if sheetName in self.wb.sheetnames: #判断sheet 名是否存在
try:
sheet = self.wb[sheetName]
return sheet
except Exception as e:
raise e
else: #不存在抛出异常 sheetName not found
raise Exception('sheetName not found')
def get_sheet_by_index(self, index: int): #通过sheet 下标获取sheet 对象
if isinstance(index, int): #判断下标是否是int类型
try:
sheet = self.wb.worksheets[index]
return sheet
except Exception as e:
raise e
else: #下标不是int类型,抛出index type error
raise Exception('index type error')
def get_sheet_by_sheetName_index(self, sheetNameIndex:int): #通过sheet 名下标获取sheet 对象
if isinstance(sheetNameIndex, int): #判断下标是否是int类型
try:
sheet = self.wb[self.wb.sheetnames[sheetNameIndex]]
return sheet
except Exception as e:
raise e
else: #下标不是int类型,抛出sheetNameIndex type error
raise Exception('sheetNameIndex type error')
def get_min_row(self, sheet) -> int: #获取有效数据区域的最小行号
return sheet.min_row
def get_max_row(self, sheet) -> int: #获取有效数据区域的最大行号
return sheet.max_row
def get_min_cols(self, sheet) -> int: #获取有效数据区域的最小列号
return sheet.min_column
def get_max_cols(self, sheet) -> int: #获取有效数据区域的最大列号
return sheet.max_column
def get_row(self,sheet, rowNo: int) -> tuple : #获取sheet 中某一行的对象,返回一个tuplp
#判断rowNo 是否是int 类型,rowNo 要大于0 小于等于最大行号(从第一行开始操作)
if isinstance(rowNo, int) and 0 < rowNo <= self.get_max_row(sheet):
try:
return list(sheet.rows)[rowNo-1] #行的下标是从1开始,sheet.row[1]表示第一行
except Exception as e:
raise e
else: #rowNo 不是int类型或rowNo 不在范围抛出rowNo not found
raise Exception('rowNo not found')
def get_row_values(self, sheet, rowNo:int) -> list: #获取sheet 中某一行cell内容,返回一个list,
# 判断rowNo 是否是int 类型,rowNo 要大于0 小于等于最大行号(从第一行开始操作)
if isinstance(rowNo, int) and 0 < rowNo <= self.get_max_row(sheet):
try:
row_values =[] #储存行数据
#遍历行对象,返回一行的cell 值
for cell in list(sheet.rows)[rowNo-1]: #行的下标是从1开始,sheet.row[1]表示第一行
row_values.append(cell.value)
return row_values
except Exception as e:
raise e
else: #rowNo 不是int类型或rowNo 不在范围抛出rowNo not found
raise Exception('rowNo not found')
def get_column(self, sheet, colsNo:int) -> tuple: #获取sheet 中某一列的对象,返回一个tuple,
# 判断colsNo 是否是int 类型,colsNo 要大于0 小于等于最大列号(从第一列开始操作)
if isinstance(colsNo, int) and 0 < colsNo <= self.get_max_cols(sheet):
try:
return list(sheet.columns)[colsNo-1] #列的下标是从1开始,sheet.columns[1]表示第一列
except Exception as e:
raise e
else: #colsNo 不是int类型或colsNo 不在范围抛出colsNo not found
raise Exception('colsNo not found')
def get_cols_values(self, sheet, colsNo:int) -> list: #获取sheet 中某一列的内容,返回一个list,
# 判断colsNo 是否是int 类型,colsNo 要大于0 小于等于最大列号(从第一列开始操作)
if isinstance(colsNo, int) and 0 < colsNo <= self.get_max_cols(sheet):
try:
cols_values = [] #储存列数据
# 遍历列对象,返回一列的cell 值
for cell in list(sheet.columns)[colsNo-1]: #列的下标是从1开始,sheet.columns[1]表示第一列
cols_values.append(cell.value)
return cols_values
except Exception as e:
raise e
else: #colsNo 不是int类型或colsNo 不在范围抛出colsNo not found
raise Exception('colsNo not found')
def get_cell_value(self, sheet, rowNo:int, colsNo:int):
#判断rowNo,colsNo 是否是int 类型
if isinstance(rowNo, int) and isinstance(colsNo, int):
try:
# 根据单元格的坐标获取单元格中的值,下标从1开始,
# sheet.cell(row=1,column =1).value 表示第一行第一列的值
return sheet.cell(row=rowNo, column=colsNo).value
except Exception as e:
raise e
else: #rowNo,colsNo 不是int类型抛出rowNo or colsNo not found
raise Exception('rowNo or colsNo not found')
def get_cell_obj(self,sheet, rowNo:int, colsNo:int): #根据单元格的坐标获取单元格对象
if isinstance(rowNo, int) and isinstance(colsNo, int):
try:
# 根据单元格的坐标获取单元格对象
return sheet.cell(row=rowNo, column=colsNo)
except Exception as e:
raise e
else:
raise Exception('rowNo or colsNo not found ')
#通过坐标获取区域内的单元格值,列和行都是从1开始
def get_some_values(self, sheet, minRowNo:int, minColsNo:int, maxRowNo:int, maxColsNo:int) -> list:
#判断行号和列号是否是int 类型
if isinstance(minRowNo, int) and isinstance(minColsNo, int) \
and isinstance(maxRowNo, int) and isinstance(maxColsNo, int):
#最小行号,最小列号不能小于最小值,最大行号,最大列号不能大于最大值,最小值不能大于最大值
if minRowNo < self.get_min_row(sheet) or minColsNo < self.get_min_cols(sheet)\
or maxRowNo < minRowNo or maxColsNo < minColsNo \
or maxRowNo > self.get_max_row(sheet) or maxColsNo > self.get_max_cols(sheet):
raise Exception('No. value is error') #抛出异常No. value is error
else:
try:
values = [] #储存区间的cell值
for i in range(minRowNo,maxRowNo+1): #遍历区间行
row_values = [] #储存区间行的cell值
for j in range(minColsNo, maxColsNo+1): #遍历区间列
row_values.append(sheet.cell(row=i, column=j).value) #把每行的列数据储存在row_values
values.append(row_values) #把区间行数据存储在values
return values #list返回区间所有的cell 值
except Exception as e:
raise e
else:
raise Exception('minRowNo or minColsNo or maxRowNo or maxColsNo not found')
# 根据单元格的坐标向单元格写入数据,下标从1开始,并确定字体颜色和单元格背景颜色,ft;字体颜色,bg:背景颜色
def write_cell(self, sheet, content, rowNo:int, colsNo:int, ft=None, bg=None):
# 判断行号和列号是否是int 类型
if isinstance(rowNo, int) and isinstance(colsNo, int):
#判断行号和列号范围,行号和列号都从第一行,第一列开始
if 0 < rowNo <= self.get_max_row(sheet) and 0 < colsNo <= self.get_max_cols(sheet):
try:
sheet.cell(row=rowNo, column=colsNo).value = content #写入要写入的数据
if ft: #判断字体颜色是否为空
#确定写入的字体颜色
sheet.cell(row=rowNo, column=colsNo).font = Font(color=self.RGBDict[ft])
if bg: #判断背景颜色是否为空
#确定写入的单元格背景颜色,fill_type 填充类型,solid 全部填充,fgColor 填充颜色
sheet.cell(row=rowNo, column=colsNo).fill = PatternFill(fill_type='solid',
fgColor=self.RGBDict[bg])
self.save()
except Exception as e:
raise e
else:
raise Exception('rowNo or colsNo out of range')
else:
raise Exception('rowNo or colsNo not found')
def write_cell_time(self, sheet, rowNo:int, colsNo:int): #根据单元格坐标写入时间
now = time.time() #获取当前时间戳
timeArray = time.localtime(now) #获取当前时间列表
currentTime = time.strftime('%Y-%m-%d %H:%M:%S', timeArray) #设置时间格式
if isinstance(rowNo, int) and isinstance(colsNo, int):
if 0 < rowNo <= self.get_max_row(sheet) and 0 < colsNo <= self.get_max_cols(sheet):
try:
sheet.cell(row=rowNo, column=colsNo).value = currentTime #写入当前时间
self.save()
except Exception as e:
raise e
else:
raise Exception('rowNo or colsNo out of range')
else:
raise Exception('rowNo or colsNo not found')
if __name__ =='__main__':
ep = ExcelParse("e:\\a.xlsx")
print(ep.load_workbook())
ep.save()
ep.create_sheet('nwesheet', 1)
print(ep.get_all_sheet_name())
print('sheet_by_name= ',ep.get_sheet_by_name('新sheet'))
print('sheet_by_index= ',ep.get_sheet_by_index(5))
Sheet=ep.get_sheet_by_sheetName_index(0)
print('minrow= ',ep.get_min_row(Sheet))
print('maxrow= ',ep.get_max_row(Sheet))
print('mincols= ',ep.get_min_cols(Sheet))
print('maxcols= ',ep.get_max_cols(Sheet))
print('getrow= ',ep.get_row(Sheet,1))
print('rowvalues= ', ep.get_row_values(Sheet, 1))
print('getcols= ',ep.get_column(Sheet,9))
print('colsvalues= ', ep.get_cols_values(Sheet, 2))
print('cellvalue= ',ep.get_cell_value(Sheet,1,7))
print(ep.get_cols_values(Sheet, 2)[1])
print('somevalues= ',ep.get_some_values(Sheet,1,1,3,5))
ep.write_cell(Sheet,'sgfgdfg',4,14,ft='yellow',bg='red')
ep.write_cell_time(Sheet,2,2)
总结
这里封装了一些常用的解析excel 文件的方法,可以作为工具类在以后工程直接使用,如需要其它的解析方法直接加进来就可以,下一篇我们介绍日志的配置与初始化