自动将多个word文件合并成一个word文件,基于python

# -*- coding: utf-8 -*-
"""
Created on Thu Apr 30 10:16:35 2020
需要先安装WPS或者OFFICE软件,自动调用对应API操作。直接就是py文件源代码,在python环境下运行即可。
主要用于将一大堆word文件合并在一个文件中,常用于在一堆文件中进行搜索,只支持docx文件,对于doc格式文件,可以先用另外一个程序自动转成docx。自己去根据情况修改dir_path等 路径即可。
@author: w
"""
import os
from os.path import abspath
from win32com import client

def main(files, final_docx):
    # 启动word应用程序
    word = client.gencache.EnsureDispatch("Word.Application")
    word.Visible = True
    # 新建空白文档
    new_document = word.Documents.Add()
    for fn in files:
        # 打开要合并的每个文件,复制其中的内容到剪切板,然后关闭文件
        fn = abspath(fn)
        temp_document = word.Documents.Open(fn)
        word.Selection.WholeStory()
        word.Selection.Copy()
        temp_document.Close()
        # 粘贴到新文档的最后
        new_document.Range()
        word.Selection.Delete()
        word.Selection.Paste()
    # 保存最终文件,关闭Word应用程序
    new_document.SaveAs(final_docx)
    new_document.Close()
    word.Quit()
    
def find_file(path, ext, file_list=[]):
    dir = os.listdir(path)
    for i in dir:
        i = os.path.join(path, i)
        if os.path.isdir(i):
            find_file(i, ext, file_list)
        else:
            if ext == os.path.splitext(i)[1]:
                file_list.append(i)
    return file_list

#先全部转换为docx文件,再合并
dir_path = "D:\我的文档\桌面\附件1文件"#批量转换文件夹
ext = ".docx"
file_list = find_file(dir_path, ext)
main(file_list,r"D:\我的文档\桌面\附件1文件\result.docx")
print(file_list)

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值