問題描述:
把多個 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/