使用python批量獲取excel的sheet名稱


這個腳本的重用是批量讀取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 + '\n')
40     excelfd = xlrd.open_workbook(excelName)
41     for sheetName in excelfd.sheet_names():
42         fd.write(sheetName + '\n')
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/')

文件結構:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM