python excel 读写的封装
Posted fyangq
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python excel 读写的封装相关的知识,希望对你有一定的参考价值。
from openpyxl import load_workbook
from common.do_config import cfg
from common.constant import DATA_FILE_PATH #用例excel存放的路径
class HandleExcel:
"""
定义处理excel的类
"""
def __init__(self,sheet_name=None):
self.filename = DATA_FILE_PATH
self.sheet_name = sheet_name
def read_data(self):
#1.打开excel
wb = load_workbook(self.filename)
# 2.定位表单
#如果有传sheetName,那么就获取指定的表单
#如果没有传sheetName ,那么就获取第一个表单
if self.sheet_name is None:
ws = wb.active
else:
ws = wb[self.sheet_name]
# 获取所有的用例数据
values = tuple(ws.iter_rows(min_row=1,max_row=1,values_only=True))
sheet_head_tuple= values[0]
#3.获取用例数据
cases_list = []
for data in tuple(ws.iter_rows(min_row=2,values_only=True)):
item = dict(zip(sheet_head_tuple,data))
cases_list.append(item)
return cases_list
def write_data(self,row,actual,result):
other_wb = load_workbook(self.filename)
actual_column = cfg.get_int("excel","actual_column")
result_column = cfg.get_int("excel","result_column")
if self.sheet_name is None:
other_ws = other_wb.active
else:
other_ws = other_wb[self.sheet_name]
if isinstance(row,int) and(2<=row<=other_ws.max_row):
other_ws.cell(row,column=actual_column,value=actual)
other_ws.cell(row, column=result_column, value=result)
other_wb.save(self.filename)
else:
print("传入的行号有误,行号应大于1的整数")
if __name__ == ‘__main__‘:
excel = HandleExcel("register-login")
print(excel.read_data())
以上是关于python excel 读写的封装的主要内容,如果未能解决你的问题,请参考以下文章