DOCX
解析
使用 parseDocx 解析和检查现有 .docx 文件
parseDocx 函数读取现有 .docx 文件并提供对其文档部件的访问。
基本用法
import { parseDocx } from "@office-open/docx";
import { readFileSync } from "node:fs";
const data = new Uint8Array(readFileSync("input.docx"));
const doc = parseDocx(data);
// 访问文档正文
console.log(doc.body);
// 访问样式(如果存在)
console.log(doc.styles);
// 访问编号(如果存在)
console.log(doc.numbering);
// 访问设置(如果存在)
console.log(doc.settings);
DocxDocument API
返回的 DocxDocument 对象包含以下内容:
| 属性 | 类型 | 说明 |
|---|---|---|
doc | ParsedDocument | 完整的已解析文档(所有部件) |
body | Element | 文档正文元素(w:body) |
styles | Element | undefined | 样式元素 |
numbering | Element | undefined | 编号定义 |
settings | Element | undefined | 文档设置 |
fontTable | Element | undefined | 字体表 |
partRefs | DocxPartRefs | 页眉、页脚、注释的引用 |
访问部件
const doc = parseDocx(data);
// 按路径获取所有部件
const body = doc.doc.get("word/document.xml");
const styles = doc.doc.get("word/styles.xml");
const header = doc.doc.get(doc.partRefs.headers.get("rId1"));
// 部件引用将关系 ID 映射到路径
for (const [rId, path] of doc.partRefs.headers) {
const header = doc.doc.get(path);
}
处理 XML 元素
已解析的元素使用 @office-open/xml 库的 Element 类型:
import { attr } from "@office-open/xml";
// 访问元素属性
const tagName = attr(doc.body, "tagName");
// 遍历子元素
for (const child of doc.body.elements ?? []) {
console.log(child.name);
}
使用场景
- 提取文本 — 遍历正文元素以提取段落文本
- 合并文档 — 解析多个
.docx文件并合并其内容 - 检查格式 — 读取样式和编号定义
- 转换 — 修改已解析的元素并重建文档