1. 程式人生 > 程式設計 >Python呼叫介面合併Excel表程式碼例項

Python呼叫介面合併Excel表程式碼例項

在工作中經常遇到需要開啟許多個excel表格,然後合併的需求,合併的同時要求格式必須原汁原味的保留。利用VBA程式碼可以比較輕鬆的解決,現在我們來看Python中如何實現。

上程式碼:

from openpyxl import Workbook
from win32com.client import Dispatch
import os
import datetime
 
 
def copy_excel_file(source_file_list,destination_file):
  run_app = Dispatch('Excel.Application')
  run_app.Visible = False # 改為True可以看到excel的開啟視窗
 
  for file in source_file_list:
    source_workbook = run_app.Workbooks.Open(Filename=file)
    destination_workbook = run_app.Workbooks.Open(Filename=destination_file)
 
    source_workbook.Worksheets(1).Copy(Before=destination_workbook.Worksheets(1))
    destination_workbook.Close(SaveChanges=True)
 
  run_app.Quit()
 
 
class ParameterGenerator:
 
  def __init__(self):
    # self.directory_path = directory_path
    self.file_lists = []
 
  def creat_xlsx(self,directory_path):
    obj = Workbook()
    if not os.path.exists(directory_path + os.sep + 'joined'):
      os.mkdir(directory_path + os.sep + 'joined')
    date = str(datetime.datetime.today())[0:10]
    obj.save(directory_path + os.sep + 'joined' + os.sep + 'joined {}.xlsx'.format(date))
 
  def get_file_list(self,directory_path):
    entry_lists = os.scandir(directory_path)
    for entry_list in entry_lists:
      if entry_list.is_file():
        if '~$' not in entry_list.path:
          self.file_lists.append(entry_list.path)
    return self.file_lists
 
  def run(self,directory_path):
    file_lists = self.get_file_list(directory_path)
    self.creat_xlsx(directory_path)
    destination_file = str(self.get_file_list(directory_path + os.sep + 'joined')[-1])
    file_lists.pop(-1)
    return file_lists,destination_file
if __name__ == "__main__":
  directory_path = r'D:\Excel目錄'
  param = ParameterGenerator()
  source_file_list,destination_file = param.run(directory_path)
  copy_excel_file(source_file_list,destination_file)

輸出是資料夾下新建一個'joined‘的資料夾,裡面有一個合併後的檔案'joined xxxx-xx-xx.xlsx',如下:

Python呼叫介面合併Excel表程式碼例項

Python呼叫介面合併Excel表程式碼例項

目前發現有兩個需要注意的問題:

1. 需要合併的檔案中不能有隱藏的表格,否則,會跳過該檔案;

2. 檔名中不可以字元意外的標記,比如括號之類的。

最後,呼叫介面的速度有點慢,以後有機會還是看openpyxl是否可以實現一下,含格式的合併。xlwings是類似的實現,估計速度也差不多的慢。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。