Python调用接口合并Excel表代码实例-创新互联

在工作中经常遇到需要打开许多个excel表格,然后合并的需求,合并的同时要求格式必须原汁原味的保留。利用VBA代码可以比较轻松的解决,现在我们来看Python中如何实现。

创新互联长期为上千家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为江源企业提供专业的成都网站设计、成都网站制作,江源网站改版等技术服务。拥有十余年丰富建站经验和众多成功案例,为您定制开发。

上代码:

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)

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


本文题目:Python调用接口合并Excel表代码实例-创新互联
文章分享:http://myzitong.com/article/dccosc.html