python 合并word_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")

大家可以试试看

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值