@classmethod def get_excel_data(cls, excel_name, sheet_name, case_num=None): """ 读取excel文件的方法 :param excel_name: 文件名称 :param sheet_name: sheet页的名称 :param case_name: 执行的case名称 :return: """ def get_row_data(table, row): """ 获取行数据 :param table: sheet页对象 :param row: 行号 :return: """ row_data = {} # table.ncols是总列数,按列号进行遍历,(从第0列开始,总列) for col in range(0, table.ncols): # 获取指定单元格数据(行,列) cell_data = table.cell_value(row, col) ctype = table.cell(row, col).ctype if ctype == 2 and cell_data % 1 == 0.0: # ctype为2且为浮点 cell_data = int(cell_data) # 浮点转成整型 cell_data = str(cell_data) # 转成整型后再转成字符串,如果想要整型就去掉该行 if ctype == 3: # 为日期格式 date = datetime(*xldate_as_tuple(cell_data, 0)) cell_data = date.strftime('%Y-%m-%d') # 获取当前单元格对应的列名 col_title = table.cell_value(0, col) # 当前列:值 row_data[col_title] = cell_data # 对应单元格 所在标题的key,例如:用例标题_cell cell_data_key = col_title + '_cell' # 对应单元格 所在标题的位置value,例如:{'row': 2, 'col': 3} cell_data_value = {'row': row, 'col': col} # 给当前用例加上每一个内容对应的位置 '用例标题_cell': {'row': 156, 'col': 1} row_data[cell_data_key] = cell_data_value return row_data # 存放字典格式,{sheet名:[{列名1:值1,列名2:值2。。。}],[{}]} sheet_dict = {} # 组装excel文件路径 file_path = adjust_path(test_case_path + '\\' + excel_name) # 打开excel文件,并且保持原有样式 work_book = xlrd.open_workbook(filename=file_path, formatting_info=True) logger.info(f'获取用例路径为:{file_path}的文件成功') # 存放所有的sheet页的名称 sheet_names = work_book.sheet_names() # case是否运行所在的列号 run_col = int(ReadFile.get_yaml_config('test.isRun_col')) # case编号所在的列号 case_num_col = int(ReadFile.get_yaml_config('test.case_num_col')) # 遍历所有的sheet页 for sheet in sheet_names: # 拿到sheet页的内容 if sheet == sheet_name: table = work_book.sheet_by_name(sheet) # 存放列表格式, [[第一行数据],[第二行数据][第三行数据]],sheet2页的名称:[[第一行数据],[第二行数据][第三行数据]] sheet_datas = [] # 如果指定case编号 if case_num: for row in range(1, table.nrows): # 得到case编号 cell_data = table.cell_value(row, case_num_col) if cell_data == case_num: row_data = get_row_data(table, row) return row_data # 如果不指定case编号 else: for row in range(1, table.nrows): # 得到case运行状态 cell_data = table.cell_value(row, run_col) # 如果case运行状态为否,就跳过此次循环,不将此行数据加入row_data if cell_data == '否': continue row_data = get_row_data(table, row) sheet_datas.append(row_data) # 将sheet页的内容写进字典里 sheet_dict[f'{sheet}'] = sheet_datas logger.info(f'获取sheet页名称为:【{sheet_name}】的内容成功,内容为:{sheet_dict[sheet_name]}') return sheet_dict[sheet_name]
02-15
641
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交