实现步骤:
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文件
注意:待合并的word文档和merge.exe要在同一个文件夹下
5.点击merge.exe即可完成合并且生成合并的文档.docx
6.代码块生成工具
https://carbon.now.sh/