跳到主要内容
Office Open

DOCX

补丁修改

通过 DocumentOptions canonical 命令修改现有 .docx

patchDocument 先把 .docx 解析成 DocumentOptions,再按顺序执行命令并重新生成包。未编辑到的 canonical round-trip 字段会继续保留来源包信息。

#命令

命令用途
insert向 canonical 数组或嵌套集合插入条目
replace替换 canonical 字段、节点或选中文本
update深合并对象字段;数组整体替换
remove删除 canonical 节点或选中文本
move调整 canonical 数组中的条目顺序
ts
import { patchDocument } from "@office-open/docx";

const result = await patchDocument({
  data: template,
  commands: [
    {
      type: "replace",
      at: { field: "sections", route: [{ index: 0 }], text: { placeholder: "name" } },
      value: "John Doe",
    },
    {
      type: "insert",
      at: { field: "sections", route: [{ index: 0 }, { collection: "children" }] },
      position: "end",
      value: [{ paragraph: { children: ["Appendix"] } }],
    },
    { type: "update", at: { field: "title" }, set: "Quarterly Report" },
  ],
});

field 是 DocumentOptions 根字段。route 通过属性、数组索引或 id、name、reference、address 等原生身份定位节点。文本默认只匹配一处;设置 all: true 才替换全部,未命中会抛出 PatchError。

#选项

选项类型默认值
dataDataType必填
commandsreadonly DocumentPatchCommand[]必填
outputTypeOutputType"uint8array"
packageVariant"standard" | "macro" | "template" | "macroTemplate""standard"
placeholderDelimiters{ start, end }{ start: "{{", end: "}}" }