python excel 读写的封装

ⅰ亾dé卋堺 提交于 2020-03-18 17:02:09
from openpyxl import load_workbookfrom common.do_config import cfgfrom 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())
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!