学Python ,用RPA,艺赛旗RPA 2020.1全新首发免费下载 点击下载
www.i-search.com.cn/index.html?from=line1
问题描述:
把多个 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")
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")
Python 合并多个 Word 文件的 4 种方法
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")
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")
大家可以试试看

本文介绍了使用Python的RPA技术合并多个Word文档的四种方法,包括pywin32+Word/WPS的三种不同实现方式以及使用python-docx和docxcompose库的方法。详细代码示例展示了如何创建新文档,打开并复制原有内容,以及保存和关闭最终合并后的文件。
747

被折叠的 条评论
为什么被折叠?



