Python调用接口合并Excel表代码实例
2020-04-01 07:07
1256 查看
在工作中经常遇到需要打开许多个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是类似的实现,估计速度也差不多的慢。
以上就是本文的全部内容,希望对大家的学习有所帮助
您可能感兴趣的文章:
相关文章推荐
- python调用接口的4种方式代码实例
- 代码笔记 | 基于Python的净值数据接口调用代码实例
- Python选择排序、冒泡排序、合并排序代码实例
- Python对excel写入数据操作实例代码(改进无法合并最后一组数据的问题)
- Python对excel写入数据操作实例代码(改进无法合并最后一组数据的问题)
- Java编程实现NBA赛事接口调用实例代码
- 基于php的基金财务数据接口调用代码实例
- Python 调用JSON接口实例
- 基于python的短信接口调用代码示例模板
- 基于php的银行卡实名认证接口调用代码实例
- php调用快递鸟接口实例代码
- eoLinker-API_Shop_短信服务接口-调用示例代码,支持PHP、Python、Java等语言
- 详解C++调用Python脚本中的函数的实例代码
- 金蝶EAS,代码调用编码规则,注意上下文及接口实例
- python3.4学习笔记(二十五) Python 调用mysql redis实例代码
- Python测试用例生成脚本(合并相应单元格以及写入单行数据)代码实例
- Python如何把多个PDF文件合并代码实例
- 用Python调用百度OCR接口实例
- 百度定制化图像开放平台使用--调用识别接口(python3代码)
- 快递100接口调用代码实例-Java