神剑山庄资源网 Design By www.hcban.com
在工作中经常遇到需要打开许多个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',如下:
目前发现有两个需要注意的问题:
1. 需要合并的文件中不能有隐藏的表格,否则,会跳过该文件;
2. 文件名中不可以字符意外的标记,比如括号之类的。
最后,调用接口的速度有点慢,以后有机会还是看openpyxl是否可以实现一下,含格式的合并。xlwings是类似的实现,估计速度也差不多的慢。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
神剑山庄资源网 Design By www.hcban.com
神剑山庄资源网
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
神剑山庄资源网 Design By www.hcban.com
暂无Python调用接口合并Excel表代码实例的评论...
更新日志
2024年09月30日
2024年09月30日
- 孙悦.1996-伙伴【正大国际】【WAV+CUE】
- 纪钧瀚《钢琴阅读时光 雨中书店聆听轻音乐》[FLAC/分轨][399.62MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[320K/MP3][87.4MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[FLAC/分轨][184.94MB]
- 陈慧娴.2018-Priscilla-Ism演唱会3CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 郑秀文.1999-我应该得到(国)【华纳】【WAV+CUE】
- 陈家慧.2011-钢琴酒吧2CD【龙吟唱片】【WAV+CUE】
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[320K/MP3][45.01MB]
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[FLAC/分轨][109.13MB]
- 赞多《序章》[320K/MP3][45.54MB]
- 许巍.2004-每一刻都是崭新的【步升大风】【WAV+CUE】
- 群星.2024-四方馆影视原声带【韶愔音乐】【FLAC分轨】
- 陈雷.1997-安锁咧【金圆唱片】【WAV+CUE】
- 关淑怡.2013-MY.FAVORITE.SK.3CD【环球】【WAV+CUE】
- Sweety.2006-花言乔语【丰华】【WAV+CUE】