这个脚本的重用是批量读取excel并获取每个excel的所有sheet名输出到一个文件中。
环境:python 3.7.3
1 # -*- coding:utf-8 -*- 2 3 ''' 4 本代码的目的是获取多个excl的sheet名,并输出到指定文件中 5 ''' 6 7 import sys 8 import xlrd 9 import os 10 import logging 11 12 13 # 设置logging.basicConfig()方法的参数和配置logging.basicConfig函数 14 FORMAT = '[%(funcName)s: %(lineno)d]: %(message)s' 15 LEVEL = logging.INFO 16 logging.basicConfig(level = LEVEL, format=FORMAT) 17 18 # 保存输出sheet name 19 output_file = './SheetNameList.txt' 20 21 # init function 22 def get_obj_list(dir_name): 23 filelist = os.listdir(dir_name) 24 for item in filelist : 25 item = dir_name + item 26 if os.path.isfile(item) and ( item[-5:] == '.xlsx' or item[-5:] == '.xlsm'): 27 if item.find("$") != -1 or item.find("csr_example") != -1 : 28 continue 29 GetSheetNameList(item) 30 elif os.path.isdir(item): 31 item = item + '/' 32 new_obj_list = [] 33 new_obj_list = get_obj_list(item) 34 35 36 # get sheet name and save in output_file 37 def GetSheetNameList(excelName): 38 fd = open(output_file, 'a+') 39 fd.write(excelName + ' ') 40 excelfd = xlrd.open_workbook(excelName) 41 for sheetName in excelfd.sheet_names(): 42 fd.write(sheetName + ' ') 43 fd.close() 44 45 46 if __name__ == "__main__": 47 if os.path.exists(output_file): 48 os.remove(output_file) 49 get_obj_list('./excel/')
文件结构: