import xlrd import os from xlwt import * # 遍歷文件夾下所有文件 def show_files(path, all_files): # 首先遍歷當前目錄所有文件及文件夾 file_list = os.listdir(path) # 准備循環判斷每個元素是否是文件夾還是文件,是文件的話,把名稱傳入list,是文件夾的話,遞歸 for file in file_list: # 利用os.path.join()方法取得路徑全名,並存入cur_path變量,否則每次只能遍歷一層目錄 cur_path = os.path.join(path, file) # 判斷是否是文件夾 if os.path.isdir(cur_path): show_files(cur_path, all_files) else: all_files.append(cur_path) return all_files # 讀取excel文件內容 def excel(excel_path): try: wb = xlrd.open_workbook(excel_path) # 打開Excel文件 sheet_name = wb.sheet_names()[0] sheet = wb.sheet_by_name(sheet_name) # 通過excel表格名稱(rank)獲取工作表 dat = [] # 創建空list print("這個sheet一共{}行".format(sheet.nrows)) # 第二行和第三行數據 academy = sheet.row_values(1)[1] name = sheet.row_values(1)[2] phone = sheet.row_values(1)[4] student_num = sheet.row_values(2)[4] # 第六行到第二十行數據 for x in range(6,sheet.nrows-1): date = sheet.row_values(x)[0] addr = sheet.row_values(x)[1] mon_heat = sheet.row_values(x)[2] non_heat = sheet.row_values(x)[3] is_sick = sheet.row_values(x)[4] is_out = sheet.row_values(x)[5] is_party = sheet.row_values(x)[6] cell_list=[academy, name, phone, student_num,date,addr,mon_heat,non_heat,is_sick,is_out,is_party] dat.append(cell_list) print(dat) return dat except Exception as e: print(e) return [excel_path] # 將內容寫入excel表 def write_to_excel(data, path): file = Workbook(encoding='utf-8') # 指定file以utf-8的格式打開 table = file.add_sheet('data') ldata = [] num = sorted([a for a in data]) # for循環指定取出key值存入num中 # 字典數據取出后無需,需要先排序 for x in num: # for循環將data字典中的鍵和值分批的保存在ldata中 t = [int(x)] for a in data[x]: t.append(a) ldata.append(t) for i, p in enumerate(ldata): # 將數據寫入文件,i是enumerate()函數返回的序號數 for j, q in enumerate(p): table.write(i, j, q) file.save(path) # 整個流程 def organize_floder_file(floder_path,target_file_path): """ 整理文件夾下全部excel內容,並且寫入到一個新的exceL中 :param floder_path: 需要整理的文件夾絕對路徑 :param target_file_path: 寫入的文件的最終路徑 :return: """ # 一,獲取文件夾下全部文件列表 contents_list = show_files(path=floder_path, all_files=[]) print("一共有表格:{}份".format(len(contents_list))) # 二,讀取每個excel文件內容,寫入all dict all_dict = {} num = 0 for excel_path in contents_list: print(excel_path) num += 1 student_info = excel(excel_path=excel_path) for info in student_info: num += 1 all_dict[num] = info # 三,將內容寫入新的excel表中 write_to_excel(data=all_dict, path=target_file_path) organize_floder_file(floder_path="D:\\2017級",target_file_path="D:\\2017\\test.xls")