首页 技术 正文
技术 2022年11月14日
0 收藏 468 点赞 3,686 浏览 1772 个字

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

上代码:

from openpyxl import Workbook
from win32com.client import Dispatch
import os
import datetimedef 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_fileif __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是类似的实现,估计速度也差不多的慢。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,038
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,524
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,372
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,152
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,785
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,867