获取文件夹中所有的Excel和Excel对应的sheet name

import os
import openpyxl

base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
test_data_path = os.path.join(base_path, "TestDatasX")


def get_test_excel_list(file_dir):
    """获取文件夹下所有excel文件中的sheet name
    ----------------这里传一个文件路劲,要么是文件夹,要么是单个Excel
    :param file_dir: 文件可以是文件夹也可以是单个文件
    :return:    ['E:\\AutoTest_BMAPI\\TestDatasX\\search.xlsx\\search']
    """
    sheet_name_list = []
    if file_dir.endswith("xlsx") or file_dir.endswith("xls"):
        """处理单个文件,确保格式一致"""
        sheet_name_list.append(file_dir)
        return [sheet_name_list]
    else:
        """处理文件夹"""
        for root, dir_name, data_name in os.walk(file_dir):
            excel_list = []
            for i in data_name:
                if i.endswith("xlsx") or i.endswith("xls"):
                    excel_list.append(os.path.join(root, i))
            sheet_name_list.append(excel_list)
    return sheet_name_list


def get_test_sheet_names(excel_list):
    sheets_name_list = []
    if len(excel_list) == 1 and len(excel_list[0]) == 1:
        wb = openpyxl.load_workbook(excel_list[0][0])
        sheet_names = wb.sheetnames
        for sheet_name in sheet_names:
            sheets_name_list.append(os.path.join(excel_list[0][0], sheet_name))
        return sheets_name_list
    else:
        """获取多Excel的sheetName"""
        for i in excel_list:
            for j in i:
                wb = openpyxl.load_workbook(j)
                sheet_names = wb.sheetnames
                for sheet_name in sheet_names:
                    sheets_name_list.append(os.path.join(j, sheet_name))
        return sheets_name_list


def excel_path_map_sheet_name(all_excel_sheet_list):
    """
    :param all_excel_sheet_list:  根据Excel和对应的sheetName,对list做拆分,获取ExcelName和sheetName
           eg: ['E:\\pytest_selenium\\test\\TestDatasX\\search.xlsx']
    :return:    [('E:\\AutoTest_BMAPI\\TestDatasX\\search.xlsx', 'search')]
    """
    case = []
    for i in all_excel_sheet_list:
        case.append(os.path.split(i))
    return case


all_excel_path = r'E:\pytest_selenium\test\TestDatasX\listPage\test'
print(excel_path_map_sheet_name(get_test_sheet_names(get_test_excel_list(all_excel_path))))

 

posted @ 2020-07-17 13:36  小心走火  阅读(1270)  评论(0编辑  收藏  举报