有个业务需求要将上千个word文档(doc格式)合并,看着头大。。不过会python,那都不是问题。
1、安装第三方库 python_docx
pip install python_docx
2、批量将doc文档转换为docx文档(因为python操作doc文档很麻烦,docx支持得不错)
需要安装pypiwin32,因为用到了?win32com
pip install pypiwin32
import docx
import os
from glob import glob
from win32com import client as wc
base_dir = "C:\\Users\\KK.JustDoIT\\Downloads\\汇总\\报修单\\日常维修-报修单-2月"
# 批量另存为
def batch_save_as():
for p in glob(os.path.join(base_dir, '*.doc')):
new_file = p.replace('doc', 'docx')
if os.path.exists(new_file):
continue
word = wc.DispatchEx('Word.Application')
# 后台运行,不显示,不警告
wc.Visible = False
wc.DisplayAlerts = 0
doc = word.Documents.Open(p) # 目标路径下的文件
doc.SaveAs(new_file, 12, False, "", True, "", False, False, False, False) # 转化后路径下的文件 #12为docx
doc.Close()
word.Quit()
batch_save_as()
也可以转换为其他的格式,参数参考:python之office_word相关操作_hanli0902的博客-CSDN博客
3、将所有转换后的docx合并为一个新的word文档(docx)
方法一:(实测合并后有点瑕疵,格式有细微变化)
import docx
import os
from glob import glob
base_dir = "C:\\Users\\KK.JustDoIT\\Downloads\\汇总\\报修单\\日常维修-报修单-2月"
save_path = "C:\\Users\\KK.JustDoIT\\Downloads\\汇总\\报修单"
#合并操作
def combine_word_documents(files):
merged_document = docx.Document()
for index, file in enumerate(files):
sub_doc = docx.Document(file)
# Don't add a page break if you've reached the last file.
if index < len(files)-1:
sub_doc.add_page_break()
for element in sub_doc.element.body:
# print(element)
merged_document.element.body.append(element)
merged_document.save(os.path.join(save_path, 'merge.docx'))
# 执行
path_list = glob(os.path.join(base_dir, '*.docx'))
combine_word_documents(path_list)
方法二:(实测格式无问题)
需要安装docxcompose
pip install docxcompose
import docx
import os
from glob import glob
from docxcompose.composer import Composer
base_dir = "C:\\Users\\KK.JustDoIT\\Downloads\\汇总\\报修单\\日常维修-报修单-2月"
save_path = "C:\\Users\\KK.JustDoIT\\Downloads\\汇总\\报修单"
def combine_all_docx(files_list):
number_of_sections=len(files_list)
master = docx.Document()
composer = Composer(master)
for i in range(1, number_of_sections):
doc_temp = docx.Document((files_list[i]))
composer.append(doc_temp)
composer.save(os.path.join(save_path, 'merge.docx'))
# 执行
path_list = glob(os.path.join(base_dir, '*.docx'))
combine_all_docx(path_list)
|