利用 Python 批量合并 Word 文档
利用 Python 批量合并 Word 文档

最近一个亲戚的工作要求经常性的合并大量 Word 文档为一个文档,手动合并耗时且易错,所以到网上搜罗了一些代码,帮他写了一个 Python 脚本
使用前请安装好 Python 和成功配置相应的环境变量,我的 Python 版本为 3.8.2
需要额外安装的模块
需要额外安装 win32com、docx、docxcompose,分别输入以下代码安装:
pip install pypiwin32
pip install python-docx
pip install docxcompose
脚本内容
import os
from glob import glob
from win32com import client as wc
from docx import Document
from docxcompose.composer import Composer
cwd = os.getcwd()
#获取doc
doc_files = glob(cwd+"\\Word\\*.doc*")
doc_files.sort()
# 将doc文件转化为docx
word = wc.Dispatch("Word.Application") # 打开word应用程序
for file in doc_files:
doc = word.Documents.Open(file) # 打开word文件
doc.SaveAs("{}x".format(file), 12) # 另存为后缀为".docx"的文件
doc.Close() # 关闭原来word文件
if '.docx' in file:
os.remove(file)
os.rename(file + 'x', file)
word.Quit()
# 合并docx
result=[]
def search(path=".", name=""):
for item in os.listdir(path):
item_path = os.path.join(path, item)
if os.path.isdir(item_path):
search(item_path, name)
elif os.path.isfile(item_path):
if name in item:
global result
result.append(item_path)
print (item_path)
search(path=cwd+'\\Word', name=".docx")
files = result
def combine_all_docx(filename_master,files_list):
number_of_sections=len(files_list)
master = Document(filename_master)
master.add_page_break() # 强制新一页
composer = Composer(master)
for i in range(1, number_of_sections):
doc_temp = Document(files_list[i])
doc_temp.add_page_break() # 强制新一页
composer.append(doc_temp)
composer.save("合并结果.docx")
combine_all_docx(result[0],result)
print("...合并完成...")
后续操作
在该脚本的目录下创建一个 Word 文件夹,然后将需要合并的 Word 文档复制(最好是复制进去,保留原文档)到该文件夹中
默认的合并顺序是按文件名排序,如果想自定义顺序的话,将文档名字前面添加 01、02、03、... 即可
最后运行该脚本,即可将文档合并为 合并结果.docx 的文档
评论