Python 合并多个 Word 文件的 4 种方法

问题描述:

把多个 Word 文档合并为一个,保留原来的内容以及全部格式。

方法一,使用扩展库pywin32+Word/WPS

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()

方法二:使用pywin32+Word/WPS

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()

main(["1.docx","2.docx","3.docx","4.docx"],r"C:\result.docx")

方法三:使用pywin32+Word/WPS

from os.path import abspath
from win32com import client

# 启动word应用程序
word = client.gencache.EnsureDispatch("Word.Application")
word.Visible = True
# 新建空白文档
new_document = word.Documents.Add()

for fn in fils[::-1]:
    fn = abspath(fn)
    new_document.Application.Selection.Range.InsertFile(fn)
# 保存最终文件,关闭Word应用程序
new_document.SaveAs(final_docx)
new_document.Close()
word.Quit()

main(["1.docx","2.docx","3.docx","4.docx"],r"C:\result.docx")

方法四:使用python-docx扩展库和docxcompose扩展库

from docx import Document
from docxcompose.composer import Comoser

def main(files,final_docx):
    new_document = Document()
    composer = Comoser(new_document)
    for fn in files:
        composer.append(Document(fn))
    composer.save(final_docx)

main(["1.docx","2.docx","3.docx","4.docx"],r"C:\result.docx")

大家可以试试看

更多RPA知识,请访问艺赛旗社区:https://support.i-search.com.cn/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章