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

如何在.docx文档页眉的指定文本后添加自定义内容?

解决方案

要定位并修改Word文档页眉中的文本,你需要通过python-docx访问文档的**节(Section)和对应的页眉(Header)**对象——原代码仅遍历了正文段落(document.paragraphs),所以无法触及页眉内容。以下是修改后的完整代码:

import os
import shutil
from docx import Document
import requests
from senhaapi import API_KEY
import json
from docxtpl import DocxTemplate

ans = read_multiple_choice(
    "Escolha a matéria da prova que será submetida",
    [{"label": "Português", "value": "portugues"},
     {"label": "Matemática", "value": "matematica"},
     {"label": "Geografia", "value": "geografia"},
     {"label": "História", "value": "historia"},
     {"label": "Física", "value": "fisica"},
     {"label": "Química", "value": "quimica"},
     {"label": "Literatura", "value": "Literatura"},
     {"label": "Inglês", "value": "ingles"},
     {"label": "Espanhol", "value": "espanhol"}, ],
)

if ans == "portugues":
    file_response = read_file("Enviar")
    file_name = file_response.name

    if not file_name.endswith(".docx"):
        display("A prova enviada deve estar no formato .docx", size='medium')
    else:
        script_dir = os.getcwd()
        destination_dir = os.path.join(script_dir, "foo/bar")
        os.makedirs(destination_dir, exist_ok=True)
        original_file_path = os.path.join(destination_dir, file_name)
        with open(original_file_path, "wb") as destination_file:
            shutil.copyfileobj(file_response.file, destination_file)

        document = Document(original_file_path)
        texto_a_adicionar = " Prova Adaptada"  # 前置空格避免与原文本粘连

        # 遍历文档所有节(适配多节不同页眉的场景)
        for section in document.sections:
            header = section.header
            # 遍历页眉内的所有段落
            for paragraph in header.paragraphs:
                if "Instruções:" in paragraph.text:
                    # 在目标段落末尾追加文本
                    paragraph.add_run(texto_a_adicionar)
                    # 若只需修改第一个匹配的页眉,可取消下面的break注释
                    # break
            # 若只需处理第一个节的页眉,可取消下面的break注释
            # break

        modified_file_path = os.path.join(destination_dir, "modified_" + file_name)
        document.save(modified_file_path)

else:
    display("Selecione uma opção válida", size='medium')

关键修改说明:

  • 访问页眉对象:Word文档的页眉属于每个Section(节),需通过section.header获取对应节的页眉实例。
  • 定位目标文本:遍历页眉的所有段落,检查段落文本是否包含Instruções:。
  • 追加文本:找到目标段落后,用paragraph.add_run()在段落末尾添加内容,前置空格保证格式美观。
  • 多节适配:代码默认遍历所有节的页眉;若只需处理第一个节的页眉,可取消代码中对应break语句的注释。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 05:12:43