首页 > 解决方案 > 通过 Python 在 *.docx 文件的标头中添加标签

问题描述

我有一个问题:我正在开发一个项目,该项目使用 Python 和python-docx在当前文件夹中的 .docx 文件的标题中自动插入文本标签。但它什么也做不了。这是代码。对一些糟糕的处决感到抱歉。我只是这个编码方面的业余爱好者。

from docx import Document
import os

path = os.path.dirname(os.path.realpath('__file__'))
print(path)

def label(docFileName):
    document = Document(docFileName)
    section = document.sections[0]
    header = section.header
    header

    header.is_linked_to_previous = True

    header = document.sections[0].header
    paragraph = header.paragraphs[0]
    paragraph.text = "Left Header\t[CONFIDENTIAL]\tRight Header"
    paragraph.style = document.styles["Normal"]

    return print("Labeled")

for file in os.listdir():
    if file.endswith(".docx"):
        docFileName = os.path.join(path,file)
        print(docFileName)
        label(docFileName)

标签: pythonlabelpython-docx

解决方案


放下header.is_linked_to_previous = True线。这基本上删除了标题。如果您有意删除现有标题,请header.is_linked_to_previous = False在该header = document.sections[0].header行之后设置,然后再访问其段落。


推荐阅读