利用Python实现word文档合并

实现步骤:
1.安装依赖

pip install docx
pip install docxcompose
pip install pyinstaller // 将py文件打包成exe文件的库

2.编写代码merge.py

import os
from docx import Document
from docxcompose.composer import Composer
import sys


# 定义合并文档的函数
def merge_doc(source_file_path_list, target_file_path):
    """
    :param source_file_path_list: 源文件路径列表
    :param target_file_path: 目标文件路径
    """
    # 填充分页符号文档
    page_break_doc = Document()
    page_break_doc.add_page_break()
    # 定义新文档
    target_doc = Document(source_file_path_list[0])
    target_composer = Composer(target_doc)
    for i in range(len(source_file_path_list)):
        # 跳过第一个作为模板的文件
        if i == 0:
            continue
        # 填充分页符文档
        print(source_file_path_list)
        try:
            target_composer.append(page_break_doc)
        except Exception as err:
            print(err)
            return
        # 拼接文档内容
        f = source_file_path_list[i]
        target_composer.append(Document(f))
    # 保存目标文档
    target_composer.save(target_file_path)


if __name__ == '__main__':
    # 原文件夹绝对路径, python能自动找到当前文件夹在当前电脑上的绝对路径
    current_path = os.path.abspath('.')
    source_path = rf'{current_path}'
    # 目标文件路径
    target_file = rf'{current_path}/合并的文档.docx'
    # print(target_file)
    # input("合并成功!输入任意字符结束")
    source_file_list = os.listdir(source_path)
    new_list = []
    for item in source_file_list:
        if item.endswith('.docx'):
            new_list.append(item)
    # 获取源文件夹内内文件列表
    source_file_list_all = []
    for file in new_list:
        source_file_list_all.append(source_path + '\\' + file)
    # 调用合并文档函数
    try:
        merge_doc(source_file_list_all, target_file)
        input("文档合并成功!输入任意字符结束对话框")
    except Exception as e:
        print(e)
        input("出错了, 输入任意字符结束")

3.执行打包exe指令

pyinstaller -F merge.py

4.等待打包成功,生成exe文件
![在这里插入图片描述](https://img-blog.csdnimg.cn/493f79d554724d5287c04cadee65e131.png
注意:待合并的word文档和merge.exe要在同一个文件夹下
5.点击merge.exe即可完成合并且生成合并的文档.docx
在这里插入图片描述
6.代码块生成工具
https://carbon.now.sh/
在这里插入图片描述

  • 9
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 10
    评论
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员禅心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值