python腳本:將指定目錄下全部excel的全部sheet單獨生成新表

注:
1.自行安裝python2.7,安裝openpyxl這個第三方庫(!!!版本爲1.5.8。最新版本爲2.4.6,ExcelWriter這個類會多一個archive入參,這裏用不到,入參一個workbook便可)
2.將倒數第二行代碼中的路徑替換成excel所在目錄(不是excel的絕對路徑)。
3.excel格式爲xlsx,若是不是執行前先修改下格式。
4.類名、類對象名自行替換下,,,

1
#coding:utf-8 2 import os 3 import sys 4 import time 5 import shutil 6 from openpyxl.reader.excel import load_workbook 7 from openpyxl.workbook import Workbook 8 from openpyxl.writer.excel import ExcelWriter 9 10 reload(sys) 11 sys.setdefaultencoding('utf8') 12 #wb = load_workbook() 13 14 class DaibiChang(object): 15 16 def __init__(self, path): 17 self.path = path 18 19 def run(self): 20 DaibiChang.SplitExcel(self.path) 21 22 @staticmethod 23 def SplitExcel(dir_path): 24 file_list = os.listdir(dir_path) 25 dir_name = [filename.split('.')[0] for filename in file_list if filename.endswith('xlsx')] 26 os.chdir(dir_path) 27 for item in dir_name: 28 try : 30 shutil.rmtree(item) 31 except: 32 pass 33 finally: 34 os.mkdir(item) 35 36 file_path = [os.path.join(dir_path, filename) for filename in file_list if filename.endswith('xlsx')] 37 content_list = [] 38 for path in file_path: 39 wb = load_workbook(path) 40 sheet_names = wb.get_sheet_names() 41 for index,sheetname in enumerate(sheet_names): 42 wb1 = Workbook() 43 ew = ExcelWriter(workbook = wb1) 44 wb1.worksheets[0] = wb.get_sheet_by_name(sheetname) 45 abs_path = '\\'.join([dir_path, os.path.split(path)[1].split('.')[0], sheetname+'.xlsx']) 46 if os.path.exists(abs_path): 47 abs_path.replace(sheetname,'{0}{1}'.fortmat(sheetname,time.time())) 48 ew.save(abs_path) 49 50 51 if __name__ == '__main__': 52 daibichang = DaibiChang(u'E:\\umac_local\\mme_41\\before_upgrade\\alarm') 53 daibichang.run()
相關文章
相關標籤/搜索