按原样复制 1 个 docx 文件的标题并使用 Python docx 将其粘贴到其他 docx(包括字体样式和徽标/图像等)

问题描述 投票:0回答:0

如何使用 python docx 复制一个文件的标题并将其粘贴到其他文件?我已经写了一些代码,但它给出了一个错误。

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
C:\Users\HP15DA~1\AppData\Local\Temp/ipykernel_7648/3264864237.py in <module>
     19 # Set the header of the first section in the new document to the new_header
     20 
---> 21 new_doc.sections[0].header = new_header
     22 
     23 # Save the new document

AttributeError: can't set attribute`
from docx import Document

# Open the source document
source_doc = Document('1.docx')

# Get the header from the source document
header = source_doc.sections[0].header

# Create a new document
new_doc = Document()

# Copy the content of the header to the new document
new_header = new_doc.sections[0].header
#new_header._element.remove_all()
for child in header._element:
    new_header._element.append(child)
#print(new_header)

# Set the header of the first section in the new document to the new_header

new_doc.sections[0].header = new_header

# Save the new document
new_doc.save('newument.docx')

python docx text-processing python-docx
© www.soinside.com 2019 - 2024. All rights reserved.