Python 合併多個 Word 文件的 4 種方法

問題描述:

把多個 Word 文檔合併為一個,保留原來的內容以及全部格式。

方法一,使用擴展庫pywin32+Word/WPS

<code>from os.path import abspath 
from win32com import client

def main(files, final_docx):
\t# 啟動word應用程序
\tword = client.gencache.EnsureDispatch("Word.Application")
\tword.Visible = True
\t# 新建空白文檔
\tnew_document = word.Documents.Add()
\t
/<code>

方法二:使用pywin32+Word/WPS

<code>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")

/<code>

方法三:使用pywin32+Word/WPS

<code>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")

/<code>

方法四:使用python-docx擴展庫和docxcompose擴展庫

<code>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")

/<code>
<code>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")

/<code>
Python 合併多個 Word 文件的 4 種方法

<code>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")

/<code>
<code>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")

/<code>

大家可以試試看


分享到:


相關文章: