1、環境
代碼運行環境:python3.7
相關的庫:xlrd、xlwt
2、目的
通過xlrd庫讀取各個表格的數據,通過xlwt庫將讀取到的數據寫入到一個表格中。
3、實現
在工程目錄下,有一個test目錄,存放的是待合並的表格,輸出表格為merge.xls,就輸出在當前工程目錄下。每個合並的表格中我只需要"body"這個sheet,而且這個sheet中的數據格式都是按照下面的格式存放的。
實現的代碼如下:
1 # encoding: utf-8 2 3 ''' 4 本代碼的作用是將多個表格合並為一個表格。 5 ''' 6 7 import os 8 import xlrd 9 import xlwt 10 import logging 11 12 # 設置logging.basicConfig()方法的參數和配置logging.basicConfig函數 13 FORMAT = '[%(funcName)s: %(lineno)d]: %(message)s' 14 LEVEL = logging.INFO 15 logging.basicConfig(level = LEVEL, format=FORMAT) 16 17 excel_content = [] 18 output_file = './merge.xls' 19 20 # 打開表格,獲取信息 21 def get_obj_list(dir_name): 22 filelist = os.listdir(dir_name) 23 for item in filelist : 24 item = dir_name + item 25 if os.path.isfile(item) and (item[-4:] == '.xls' or item[-5:] == '.xlsx' or item[-5:] == '.xlsm'): 26 if item.find("$") != -1: 27 continue 28 merge_excel(item) 29 elif os.path.isdir(item): 30 item = item + '/' 31 get_obj_list(item) 32 33 34 # 獲取單個表格的信息 35 def merge_excel(excelName): 36 excelfd = xlrd.open_workbook(excelName) 37 for sheet in excelfd.sheet_names(): 38 if sheet == 'body': 39 print (excelName) 40 sheet_content = excelfd.sheet_by_name(sheet) 41 header = sheet_content.cell(0, 0).value 42 if header == u'高校名稱': # 去掉標題行 43 row = 1 44 else: 45 row = 0 46 while row < sheet_content.nrows: 47 college = sheet_content.cell(row, 0).value 48 institute = sheet_content.cell(row, 1).value 49 built_time = sheet_content.cell(row, 2).value 50 overview = sheet_content.cell(row, 3).value 51 item = [college, institute, built_time, overview] 52 excel_content.append(item) 53 row += 1 54 55 56 # 將獲取到的表格信息保存到一個表格中 57 def save_info(): 58 workbook = xlwt.Workbook(encoding = 'ascii') 59 worksheet = workbook.add_sheet('merge_info') 60 style = xlwt.XFStyle() # 初始化樣式 61 font = xlwt.Font() # 為樣式創建字體 62 font.name = 'Times New Roman' 63 font.bold = True # 黑體 64 font.underline = True # 下划線 65 font.italic = True # 斜體字 66 style.font = font # 設定樣式 67 worksheet.write(0, 0, '高校名稱') 68 worksheet.write(0, 1, '學院名稱') 69 worksheet.write(0, 2, '成立時間') 70 worksheet.write(0, 3, '人工智能學院、人工智能研究院建設情況') 71 72 for i, item in enumerate(excel_content): 73 for j in range(4): #多添加一列(序號) 74 worksheet.write(i+1, j, item[j]) 75 workbook.save(output_file) # 保存文件 76 77 78 if __name__ == "__main__": 79 80 if os.path.exists(output_file): 81 os.remove(output_file) 82 83 get_obj_list('./test/') 84 save_info()
4、輸出結果
這是我手動調整過表格格式的結果。至此,需要實現的功能都實現了。