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

如何用Python在含表格的Word DOCX文件中查找替换文本

解决Word DOCX(含表格)文本替换的Python方案

核心实现思路

借助python-docx库遍历文档全部内容,涵盖普通段落与表格单元格内的段落,逐个对目标文本进行查找替换,同时保留原文档格式。

操作步骤

  1. 安装依赖库
pip install python-docx
  1. 执行替换脚本
from docx import Document

def replace_target_text(doc_path, old_str, new_str, save_path):
    doc = Document(doc_path)
    
    # 处理普通段落
    for para in doc.paragraphs:
        for run in para.runs:
            if old_str in run.text:
                run.text = run.text.replace(old_str, new_str)
    
    # 处理表格单元格
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                for para in cell.paragraphs:
                    for run in para.runs:
                        if old_str in run.text:
                            run.text = run.text.replace(old_str, new_str)
    
    doc.save(save_path)

# 替换示例
if __name__ == "__main__":
    replace_target_text(
        "原始文档路径.docx",
        "to_be_replaced",
        "你需要替换成的新文本",
        "修改后文档路径.docx"
    )

关键注意点

  • 遍历run而非直接修改段落文本,是为了保留原文本的格式(如字体、颜色、加粗等),避免格式丢失。
  • 运行脚本前请关闭目标Word文档,否则会因文件占用导致保存失败。
  • 若文档包含页眉、页脚、文本框等特殊区域,需额外添加对应遍历逻辑,上述代码仅处理普通段落和表格内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 09:52:20