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

如何在Word加载项中移除指定文本块并替换为处理后内容

解决Word加载项保留原有内容、替换生成文本的方案

要实现保留文档原有内容,仅替换自动生成的文本块,你可以通过插入隐藏的首尾标记来定位目标文本范围,具体实现步骤如下:

1. 生成文本时插入首尾标记

在开始生成文本前插入起始标记,生成完成后插入结束标记,同时将标记设为隐藏文本,避免干扰用户查看:

// 生成文本前插入起始标记
async function insertStartMarker() {
  await window.Word.run(async (context) => {
    const body = context.document.body;
    body.insertText("[[STARTOF_GENERATED]]", "end");
    const startPara = body.paragraphs.getLast();
    startPara.font.hidden = true;
    await context.sync();
  });
}

// 生成文本后插入结束标记
async function insertEndMarker() {
  await window.Word.run(async (context) => {
    const body = context.document.body;
    body.insertText("[[ENDOF_GENERATED]]", "end");
    const endPara = body.paragraphs.getLast();
    endPara.font.hidden = true;
    await context.sync();
  });
}

2. 修改转换函数,定位并替换生成文本

在convertWordToHtml函数中,通过搜索标记找到目标范围,删除旧的生成内容后插入格式化后的HTML:

async function convertWordToHtml(finalText: string) {
  await window.Word.run(async (context: any) => {
    const body = context.document.body;
    body.font.name = "Open Sans";
    body.font.size = 11;
    body.lineSpacing = 1.5;

    const converter = new showdown.Converter({ simpleLineBreaks: true, noHeaderId: true });
    const html = converter.makeHtml(finalText);

    // 搜索首尾标记
    const startMatches = body.search("[[STARTOF_GENERATED]]", { matchWildcards: false });
    const endMatches = body.search("[[ENDOF_GENERATED]]", { matchWildcards: false });

    if (startMatches.length > 0 && endMatches.length > 0) {
      const startMarker = startMatches[0];
      const endMarker = endMatches[0];

      // 删除标记之间的旧生成内容
      const generatedRange = context.document.getRange(startMarker.end, endMarker.start);
      generatedRange.delete();

      // 清理旧标记并插入新格式化内容
      startMarker.delete();
      endMarker.insertHtml(html, "before");
      endMarker.delete();
    } else {
      // 首次生成无标记时,直接插入内容
      body.insertHtml(html, "end");
    }

    await context.sync();
  });
}

关键说明

  • 用隐藏文本作为标记,既不会影响用户体验,又能精准定位生成内容的范围;
  • 若文档中存在多组标记,可根据实际逻辑调整搜索规则(比如取最后一组标记);
  • 替换时先删除旧内容再插入新HTML,确保原有内容完全保留。

内容的提问来源于stack exchange,提问作者Lucas Gardini Dias

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 00:42:26