python 使用 openpyxl 模塊合並多個Excel內容到一個Excel文件里


python 使用 openpyxl 模塊合並多個Excel內容到一個Excel文件里 

  注意:

  • 只支持.xlsx格式,2003,2007版本的.xls文件不支持
  • 文件絕對路徑中,文件名或文件夾名稱中不能有任何空格出現。
  1 # *-* coding-utf-8 *-*
  2 import sys
  3 
  4 # 在path里追加,python.exe解釋器,目錄下的第三方模塊的文件夾路徑。以免在cmd.exe中運行時,找不到模塊。【注意:】在不同的PC上時,需要更改此路徑
  5 sys.path.append(r'C:\Users\gk\AppData\Local\Programs\Python\Python37\Lib\site-packages')
  6 
  7 import os
  8 
  9 def merge_Excel(excelpath_list, new_excel_path=os.path.dirname(__file__)+'\\合並的文件.xlsx', source_all_sheet=True):
 10     '''
 11     將多個excel文件,合並到一個新的excel里。
 12     :param excelpath_list: 要合並的excel文件路徑列表
 13     :param new_excel_path: 合並后的excel文件路徑
 14     :param source_all_sheet: 是否合並源Excel中的所有工作表
 15     :return:
 16     '''
 17     if len(excelpath_list) == 0:
 18         return False
 19     from openpyxl import Workbook
 20     from openpyxl import load_workbook
 21 
 22     sheet_count = 0
 23 
 24     # 實例化一個新的工作簿,用戶保存合並的數據
 25     wb_new = Workbook()
 26 
 27     for excel_path in excelpath_list:  # 第1層循環,遍歷所有的Excel文件 =========================================
 28         wb = load_workbook(excel_path)  # 載入源excel文件,獲取工作簿
 29         wb.guess_types = True  # 猜測格式類型
 30         # 獲取 工作簿中的所有sheet
 31         if source_all_sheet:
 32             ws_all = wb.worksheets
 33         else:
 34             ws_all = [wb.active]
 35 
 36         for sheet in ws_all:  # 第2層循環,遍歷每個Excel的sheet =========================================
 37             # 獲取 sheet中的有效行數、列數
 38             count_row = 0  # 工作表的有效行數
 39             count_col = 0  # 工作表的有效列數
 40             for row in sheet.rows:
 41                 count_row += 1
 42             for col in sheet.columns:
 43                 count_col += 1
 44             if count_row==0 or count_col==0: #如果有效行數/列數為0,代表當前表沒有數據 [重要]
 45                 continue
 46 
 47             # 讀取sheet的內容,寫入到新工作簿的工作表中
 48             list_all = []
 49             row_range = sheet[1:count_row]
 50             list_row = []
 51             tag=False
 52 
 53             for row in row_range:
 54                 if  type(row) is not tuple:   # 判斷row的類型是不是元祖,如果不是元祖,代表當前sheet只有一行數據,row就是單元格對象; 反之,row是包含了整行單元格對象的元祖
 55                     tag = True
 56                     break
 57             if tag:  # 代表當前sheet只有一行數據,row就是單元格對象;
 58                 for cell in row_range:  # 第3層循環  遍歷工作表的行、列。封裝數據  ==============================
 59                      list_row.append(cell.value)
 60                 list_all.append(list_row)  # 將1行中的所有列的數據(列表類型),在添加進總列表里
 61             else: #  代表   當前sheet有多行數據
 62                 for row in row_range:
 63                     list_row = []  # 清空
 64                     for cell in row:
 65                         list_row.append(cell.value)  # 遍歷1行中的每列數據,讀取后,添加進一個列表
 66                     list_all.append(list_row)  # 將1行中的所有列的數據(列表類型),在添加進總列表里
 67 
 68             # 將源sheet中提取后,封裝的數據寫入新的工作表
 69             ws_temp = wb_new.create_sheet('sheet-%s' % sheet_count)
 70             for item in list_all:  # 第3層循環  將提取的原sheet數據 循環寫入到新的sheet里
 71                 # 判斷用戶選擇是否合並到一個sheet
 72                 ws_temp.append(item)
 73             sheet_count += 1
 74 
 75     # 保存文件
 76     wb_new.save(new_excel_path)
 77     return True
 78 
 79 def run():
 80     # 1. 獲取用戶設置的文件保存路徑
 81     ini_path=os.path.join(os.path.dirname(__file__),"P18Config",'Path_User.ini')     # 組織 Path_User.ini 文件的路徑
 82 
 83     # 從 Path_User.ini 里獲取 用戶 設置的 文件導出路徑
 84     with open(ini_path,'rt',encoding="utf-8") as f:
 85         user_path= f.readline().strip()
 86     # 組織當前日期的文件夾路徑
 87     import time
 88     folder_path=user_path+os.sep+time.strftime("%Y-%m-%d")
 89 
 90     # 2. 組織 合成后的新excel文件的絕對路徑,判斷該文件,是否已經存在
 91     new_excel_path = os.path.join(folder_path, time.strftime("%Y-%m-%d") + "_全天產品數據.xlsx")
 92     if os.path.exists(new_excel_path):
 93         os.remove(new_excel_path)  # 刪除該文件
 94 
 95     # 3.組織所有要合並的excel文件的絕對路徑,添加進list
 96     list_file=os.listdir(folder_path) # 獲取日期文件夾下的所有文件名稱列表
 97     list_file_path=[ ]
 98     for item in list_file:
 99         list_file_path.append(os.path.join(folder_path,item) )
100     print(list_file_path)
101 
102     # 4.調用函數,合並 所有excel
103     res = merge_Excel(list_file_path,new_excel_path)
104     if res:
105         print("合並成功")
106 
107 
108 if __name__ == "__main__":
109     run()

 

 

 

 

 

 

 

 

 


免責聲明!

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



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