简体   繁体   English

如何使用 python 将 docx 文件的内容和 append 复制到另一个 docx 文件

[英]How to copy content of docx file and append it to another docx file using python

I want to combine multiple docx file and save it in another docx file.我想合并多个 docx 文件并将其保存在另一个 docx 文件中。 I not only want to copy all the text, but also it's formatting(runs).我不仅要复制所有文本,还要复制它的格式(运行)。 eg.例如。 bold, italics, underline, bullets, etc.粗体、斜体、下划线、项目符号等。

If you need to copy the contents of just one docx file to another, you can use this如果你只需要将一个 docx 文件的内容复制到另一个文件,你可以使用这个

from docx import Document
from docxcompose.composer import Composer

# main docx file
master = Document(r"path\of\main.docx")
composer = Composer(master)
# doc1 is the docx file getting copied
doc1 = Document(r"file\to\be\copied.docx")
composer.append(doc1)
composer.save(r"path\of\combined.docx")

If you have multiple docx files to be copied, you can try like this如果你有多个要复制的docx文件,你可以这样试试

def copy_docx(main_docx, docx_list):
    master = Document(main_docx)
    composer = Composer(master)
    for index, file in enumerate(docx_list):
        file = Document(file)
        composer.append(file)
    composer.save(r"path\of\combined.docx")


main_docx = "path\of\main.docx"
docx_list = [r"path\of\docx1.docx",
             r"path\of\docx2.docx",
             r"path\of\docx3.docx"]

copy_docx(main_docx, docx_list)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM