1. 程式人生 > 實用技巧 >獲取資料夾中所有的Excel和Excel對應的sheet name

獲取資料夾中所有的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))))