DOCX
补丁修改
通过 DocumentOptions canonical 命令修改现有 .docx
patchDocument 先把 .docx 解析成 DocumentOptions,再按顺序执行命令并重新生成包。未编辑到的 canonical round-trip 字段会继续保留来源包信息。
#命令
| 命令 | 用途 |
|---|---|
insert | 向 canonical 数组或嵌套集合插入条目 |
replace | 替换 canonical 字段、节点或选中文本 |
update | 深合并对象字段;数组整体替换 |
remove | 删除 canonical 节点或选中文本 |
move | 调整 canonical 数组中的条目顺序 |
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。
#选项
| 选项 | 类型 | 默认值 |
|---|---|---|
data | DataType | 必填 |
commands | readonly DocumentPatchCommand[] | 必填 |
outputType | OutputType | "uint8array" |
packageVariant | "standard" | "macro" | "template" | "macroTemplate" | "standard" |
placeholderDelimiters | { start, end } | { start: "{{", end: "}}" } |