You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python docx获取并替换Word文档首页页眉文本?

问题描述

需要替换Word文档页眉中的文本,尝试以下代码但未成功:

from docx import Document
document = Document(path_and_filename)
section = document.sections[0]
header = section.header
for paragraph in header.paragraphs:
    print(paragraph.text)
解决方法

针对不同的页眉结构,有几种处理方式:

  • 普通页眉段落替换
    如果页眉由普通段落组成,直接遍历段落里的run替换文本(可保留原有格式),代码如下:
from docx import Document

document = Document("目标文档路径.docx")
section = document.sections[0]
header = section.header

# 遍历页眉段落,逐个run替换文本
for paragraph in header.paragraphs:
    for run in paragraph.runs:
        run.text = run.text.replace("要替换的旧文本", "新文本")

document.save("修改后的文档路径.docx")

若无需保留格式,也可直接修改整个段落的text:

paragraph.text = paragraph.text.replace("旧文本", "新文本")
  • 页眉包含文本框的情况
    不少Word文档的页眉会用文本框排版,这种情况要遍历页眉的形状对象,找到文本框内的内容修改:
from docx import Document

document = Document("目标文档路径.docx")
section = document.sections[0]
header = section.header

# 处理页眉中的文本框内容
for shape in header.shapes:
    if shape.has_text_frame:
        for paragraph in shape.text_frame.paragraphs:
            for run in paragraph.runs:
                run.text = run.text.replace("旧文本", "新文本")

document.save("修改后的文档路径.docx")
  • 页眉链接到前一节的情况
    如果当前节的页眉设置了"链接到前一节",直接修改会无效,需要先取消链接再操作:
from docx import Document

document = Document("目标文档路径.docx")
section = document.sections[0]

# 取消页眉与前一节的关联
section.header.is_linked_to_previous = False

header = section.header
# 后续按普通段落方式修改即可
for paragraph in header.paragraphs:
    for run in paragraph.runs:
        run.text = run.text.replace("旧文本", "新文本")

document.save("修改后的文档路径.docx")

内容的提问来源于stack exchange,提问作者venkateswaran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 19:15:27