zoukankan      html  css  js  c++  java
  • 获取文件夹中所有的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	estTestDatasXlistPage	est'
    print(excel_path_map_sheet_name(get_test_sheet_names(get_test_excel_list(all_excel_path))))
  • 相关阅读:
    Web开发中的服务器跳转与客户端跳转
    Linux设置程序开机自启动
    RedHat Linux6.4下安装apache服务
    FTP错误 [ftp: connect: No route to host] 解决方法
    虚拟机ping不通主机,但是主机可以ping通虚拟机(转载)
    工作中常用的Linux命令:mkdir命令
    工作中常用的Linux命令:crontab命令
    工作中常用的Linux命令:目录
    工作中常用的Linux命令:ipcs/ipcrm命令
    【CentOS】在Centos7 下无图形界面安装 Oracle11g
  • 原文地址:https://www.cnblogs.com/nieliangcai/p/13329469.html
Copyright © 2011-2022 走看看