Python调用接口合并Excel表代码实例

  

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

  

上代码:

        从openpyxl进口工作簿   从win32com。客户端导入调度   进口操作系统   进口日期时间         def copy_excel_file (source_file_list destination_file):   run_app=调度(“Excel.Application”)   run_app。可见=False #改为真实可以看到excel的打开窗口      在source_file_list文件:   source_workbook=run_app.Workbooks.Open(文件名=文件)   destination_workbook=run_app.Workbooks.Open(文件名=destination_file)      source_workbook.Worksheets (1) .Copy (=destination_workbook.Worksheets前(1))   destination_workbook.Close (SaveChanges=True)      run_app.Quit ()         类ParameterGenerator:      def __init__(自我):   #自我。directory_path=directory_path   自我。file_lists=[]      def creat_xlsx(自我,directory_path):   obj=工作簿()   如果不是os.path。存在(directory_path +操作系统。9 +“加入”):   操作系统。mkdir (directory_path +操作系统。9 +“加入”)   日期=str (datetime.datetime.today ()) (0:10)   obj。保存(directory_path +操作系统。9 +“加入”+操作系统。9 +‘加入{}.xlsx .format(日期)      directory_path def get_file_list(自我):   entry_lists=os.scandir (directory_path)   在entry_lists entry_list:   如果entry_list.is_file ():   如果“美元~”不在entry_list.path:   self.file_lists.append (entry_list.path)   返回self.file_lists      def运行(自我,directory_path):   file_lists=self.get_file_list (directory_path)   self.creat_xlsx (directory_path)   destination_file=str(自我。get_file_list (directory_path +操作系统。9 +“加入”)[1])   file_lists.pop (1)   返回file_lists destination_file   if __name__==癬_main__”:   directory_path=r想:\ Excel目录的   param=ParameterGenerator ()   source_file_list destination_file=param.run (directory_path)   copy_excel_file (source_file_list destination_file)      

输出是文件夹下新建一个“加入”的文件夹,里面有一个合并后的文件加入xxxx-xx-xx.xlsx,如下:

  

 Python调用接口合并Excel表代码实例

  

 Python调用接口合并Excel表代码实例

  

目前发现有两个需要注意的问题:

  

1。需要合并的文件中不能有隐藏的表格,否则,会跳过该文件;

  

2。文件名中不可以字符意外的标记,比如括号之类的。

  

最后,调用接口的速度有点慢,以后有机会还是看openpyxl是否可以实现一下,含格式的合并.xlwings是类似的实现,估计速度也差不多的慢。

  

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

Python调用接口合并Excel表代码实例