实际工作中更常见的情况是:文档已经写好,章节结构齐全,只是当初没有生成目录。此时不必重排内容,在原有标题样式的基础上补一个目录域,即可得到带页码与跳转的目录。目录的生成与保存都在浏览器端完成,合同、方案这类文件无需上传到服务器,处理环节因此少了一次。
本文以一份《2026 年度产品技术报告》为例,介绍在已有文档中添加内容目录的四种做法。示例基于 Spire.Doc for JavaScript,该库以 WebAssembly 形式在浏览器端运行,字体与文档文件通过虚拟文件系统(VFS)读写。
与新建文档相比,为已有文档添加目录多了两个关键步骤:一是通过 LoadFromFile 从 VFS 载入原有文档,二是通过 Paragraphs.Insert 指定目录段落的位置。AddParagraph 总是把新段落追加到所在节的末尾,直接在其上插入目录域,目录就会出现在文末,这是已有文档中最常见的问题。
本文包含以下内容:
有关安装和项目配置,请参考 React 项目中集成 Spire.Doc for JavaScript。以下示例默认已安装 Spire.Doc 并完成 WebAssembly 模块初始化,示例文档 AddTocToExisting.docx 放在项目的 public/data/ 目录下。
在文档开头添加目录
在文档开头添加目录时,先用 AppendTOC 在新建段落上写入目录域,再用 Paragraphs.Insert(0, tocPara) 把这个段落移到文档最前面。AppendTOC 接收起始级别与结束级别两个参数,目录只收录落在该范围内的标题:
| 写法 | 收录范围 |
|---|---|
AppendTOC(1, 3) |
Heading 1 至 Heading 3 |
AppendTOC(1, 2) |
Heading 1 至 Heading 2 |
AppendTOC(2, 3) |
Heading 2 至 Heading 3 |
示例传入 (1, 3),目录收录四章、十个二级标题与两个三级标题,共 16 个条目。目录段落末尾再追加一个分页符,原有内容整体后移一页,目录独占第 1 页。
具体操作步骤如下:
- 获取 Spire.Doc 的 WASM 模块,确认已就绪。
- 将正文字体
msyh.ttc、粗体字体msyhbd.ttc与示例文档AddTocToExisting.docx载入虚拟文件系统(VFS)。 - 创建
Document对象,用LoadFromFile载入已有文档,并取得第一节。 - 新建段落,调用
AppendTOC(1, 3)写入目录域,再用AppendBreak追加分页符。 - 用
Paragraphs.Insert(0, tocPara)把目录段落移到文档开头,并在其上方插入「目 录」标题段落。 - 调用
UpdateTableOfContents更新条目与页码,用SaveToFile保存,再从 VFS 读出结果触发下载。
在文档开头添加目录的代码如下:
function App() {
const addTocAtStart = async () => {
// 获取 Spire.Doc WASM 模块
const docModule = window.wasmModule?.spiredoc;
// 确保 WASM 模块完全加载完成
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
// 将字体与示例文档载入 VFS
await window.spire.FetchFileToVFS('msyh.ttc', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
await window.spire.FetchFileToVFS('msyhbd.ttc', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'AddTocToExisting.docx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);
// 创建文档实例并载入已有文档
const doc = new docModule.Document();
doc.LoadFromFile({ fileName: inputFileName });
// 获取文档的第一节
const section = doc.Sections.get_Item(0);
// 新建段落并插入目录域,收录 Heading 1 至 Heading 3 的条目
const tocPara = section.AddParagraph();
tocPara.AppendTOC(1, 3);
// 目录单独占一页,原有内容另起一页
tocPara.AppendBreak(docModule.BreakType.PageBreak);
// 将目录段落移动到文档最开头
section.Paragraphs.Insert(0, tocPara);
// 目录页版头:目录条目本身不含标题行,这里补一行「目 录」
const titleFormat = new docModule.CharacterFormat(doc);
titleFormat.FontName = '微软雅黑';
titleFormat.FontSize = 18;
titleFormat.Bold = true;
titleFormat.TextColor = docModule.Color.FromArgb(31, 40, 70);
const titlePara = section.AddParagraph();
titlePara.AppendText('目 录').ApplyCharacterFormat(titleFormat);
titlePara.Format.AfterSpacing = 14;
section.Paragraphs.Insert(0, titlePara);
// 更新目录,填充条目与页码
doc.UpdateTableOfContents();
// 定义输出文件名并保存
const outputFileName = '在文档开头添加目录.docx';
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
// 释放资源
doc.Dispose();
// 从 VFS 读取生成的文件,触发下载
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>在文档开头添加目录</h1>
<button onClick={addTocAtStart}>
添加目录
</button>
</div>
);
}
export default App;
目录被放到文档最前面并独占一页,原有的封面、正文与页脚页码保持不变。由于目录占据了第 1 页,正文第一章顺延到第 3 页,目录中的页码也随之刷新:

在文档指定位置添加目录
在文档指定位置添加目录时,改动只有一处:Paragraphs.Insert 的索引不再是 0,而是目标位置。索引按正文中的子对象顺序计算,段落与表格各占一个位置,因此不能直接用段落集合的下标去找插入点。示例先遍历 Body.ChildObjects,找到第一个应用了 Heading 1 样式的段落,再把这个对象位置交给 Paragraphs.Insert,目录就落在第一章之前:封面留在第 1 页,目录从第 2 页开始。
具体操作步骤如下:
- 获取 Spire.Doc 的 WASM 模块,确认已就绪。
- 将正文字体
msyh.ttc、粗体字体msyhbd.ttc与示例文档AddTocToExisting.docx载入虚拟文件系统(VFS)。 - 创建
Document对象并载入已有文档,取得第一节。 - 遍历第一节的
Body.ChildObjects,找到第一个 Heading 1 段落所在的位置,作为目录的插入索引。 - 新建段落,调用
AppendTOC(1, 3)写入目录域并追加分页符,用Paragraphs.Insert(index, tocPara)插入到第一章之前,再补上「目 录」标题段落。 - 调用
UpdateTableOfContents更新条目与页码,保存后从 VFS 读出结果触发下载。
在文档指定位置添加目录的代码如下:
function App() {
const addTocAtPosition = async () => {
// 获取 Spire.Doc WASM 模块
const docModule = window.wasmModule?.spiredoc;
// 确保 WASM 模块完全加载完成
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
// 将字体与示例文档载入 VFS
await window.spire.FetchFileToVFS('msyh.ttc', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
await window.spire.FetchFileToVFS('msyhbd.ttc', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'AddTocToExisting.docx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);
// 创建文档实例并载入已有文档
const doc = new docModule.Document();
doc.LoadFromFile({ fileName: inputFileName });
// 获取文档的第一节
const section = doc.Sections.get_Item(0);
// 在正文对象中定位第一章标题;表格也占用一个位置,不能直接用段落集合的下标
let insertIndex = 0;
const children = section.Body.ChildObjects;
for (let i = 0; i < children.Count; i++) {
const obj = children.get_Item(i);
if (obj.DocumentObjectType === docModule.DocumentObjectType.Paragraph && obj.StyleName === 'Heading1') {
insertIndex = i;
break;
}
}
// 新建段落并插入目录域,收录 Heading 1 至 Heading 3 的条目
const tocPara = section.AddParagraph();
tocPara.AppendTOC(1, 3);
tocPara.AppendBreak(docModule.BreakType.PageBreak);
// 目录插到第一章之前:封面 → 目录 → 正文
section.Paragraphs.Insert(insertIndex, tocPara);
// 目录页版头
const titleFormat = new docModule.CharacterFormat(doc);
titleFormat.FontName = '微软雅黑';
titleFormat.FontSize = 18;
titleFormat.Bold = true;
titleFormat.TextColor = docModule.Color.FromArgb(31, 40, 70);
const titlePara = section.AddParagraph();
titlePara.AppendText('目 录').ApplyCharacterFormat(titleFormat);
titlePara.Format.AfterSpacing = 14;
section.Paragraphs.Insert(insertIndex, titlePara);
// 更新目录,填充条目与页码
doc.UpdateTableOfContents();
// 定义输出文件名并保存
const outputFileName = '在文档指定位置添加目录.docx';
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
// 释放资源
doc.Dispose();
// 从 VFS 读取生成的文件,触发下载
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>在文档指定位置添加目录</h1>
<button onClick={addTocAtPosition}>
添加目录
</button>
</div>
);
}
export default App;
目录落在封面与正文之间,封面仍是第 1 页,目录从第 2 页开始,正文从第 3 页开始:

添加自定义目录
添加自定义目录时,改为构造 TableOfContent 对象,并在构造时传入域开关串。与 AppendTOC 的区别在于插入方式:需要手动把目录对象加入段落、补齐域分隔符与域结束标记,再把对象赋给 Document.TOC。常用的域开关如下:
| 开关 | 说明 |
|---|---|
\o "1-2" |
按内置标题样式收集条目,此处表示收录 Heading 1 至 Heading 2 |
\h |
为目录条目写入超链接,点击后跳转到对应章节 |
\z |
在 Web 版式视图中隐藏页码与制表符前导符 |
\u |
按段落的大纲级别收集条目 |
示例使用 \o "1-2" \h \z \u,目录只收录四章与十个二级标题,共 14 个条目,2.2.1、2.2.2 这类三级标题不再出现。
具体操作步骤如下:
- 获取 Spire.Doc 的 WASM 模块,确认已就绪。
- 将正文字体
msyh.ttc、粗体字体msyhbd.ttc与示例文档AddTocToExisting.docx载入虚拟文件系统(VFS)。 - 创建
Document对象并载入已有文档,取得第一节。 - 用
new TableOfContent(doc, '{\\o "1-2" \\h \\z \\u}')构造目录对象,加入新建段落,补齐域分隔符与域结束标记。 - 将目录对象赋给
doc.TOC,再用Paragraphs.Insert(0, tocPara)插入到文档开头,并补上「目 录」标题段落。 - 调用
UpdateTableOfContents更新条目与页码,保存后从 VFS 读出结果触发下载。
添加自定义目录的代码如下:
function App() {
const addCustomToc = async () => {
// 获取 Spire.Doc WASM 模块
const docModule = window.wasmModule?.spiredoc;
// 确保 WASM 模块完全加载完成
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
// 将字体与示例文档载入 VFS
await window.spire.FetchFileToVFS('msyh.ttc', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
await window.spire.FetchFileToVFS('msyhbd.ttc', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'AddTocToExisting.docx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);
// 创建文档实例并载入已有文档
const doc = new docModule.Document();
doc.LoadFromFile({ fileName: inputFileName });
// 获取文档的第一节
const section = doc.Sections.get_Item(0);
// 构造带自定义域开关的目录对象:收录 Heading 1 至 Heading 2,条目带超链接
const toc = new docModule.TableOfContent(doc, '{\\o "1-2" \\h \\z \\u}');
const tocPara = section.AddParagraph();
tocPara.Items.Add(toc);
// 补齐域分隔符与域结束标记
tocPara.AppendFieldMark(docModule.FieldMarkType.FieldSeparator);
tocPara.AppendText('TOC');
tocPara.AppendFieldMark(docModule.FieldMarkType.FieldEnd);
tocPara.AppendBreak(docModule.BreakType.PageBreak);
// 将该目录绑定到文档
doc.TOC = toc;
// 将目录段落移动到文档最开头
section.Paragraphs.Insert(0, tocPara);
// 目录页版头
const titleFormat = new docModule.CharacterFormat(doc);
titleFormat.FontName = '微软雅黑';
titleFormat.FontSize = 18;
titleFormat.Bold = true;
titleFormat.TextColor = docModule.Color.FromArgb(31, 40, 70);
const titlePara = section.AddParagraph();
titlePara.AppendText('目 录').ApplyCharacterFormat(titleFormat);
titlePara.Format.AfterSpacing = 14;
section.Paragraphs.Insert(0, titlePara);
// 更新目录,填充条目与页码
doc.UpdateTableOfContents();
// 定义输出文件名并保存
const outputFileName = '添加自定义目录.docx';
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
// 释放资源
doc.Dispose();
// 从 VFS 读取生成的文件,触发下载
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>添加自定义目录</h1>
<button onClick={addCustomToc}>
添加目录
</button>
</div>
);
}
export default App;
目录条目止于二级标题,原有的三级标题不再进入目录:

通过域开关限定收录级别
域开关串决定了目录的行为,调整 \o 后的级别范围即可改变收录范围:把它改为 \o "1-3",三级标题会重新进入目录;去掉 \h,条目不再写入超链接,目录变成纯文本的页码对照表:
// 收录三级标题,不再写入超链接
const toc = new docModule.TableOfContent(doc, '{\\o "1-3" \\z \\u}');
更新已有目录的页码
更新已有目录的页码时,只需在保存前调用 UpdateTableOfContents。目录条目与页码是域的计算结果,更新域时才按当时的排版写入,因此不需要重新构造目录对象。示例载入一份已经带目录的文档(即第一个功能点的结果),在正文末尾追加第五章,再更新目录。
具体操作步骤如下:
- 获取 Spire.Doc 的 WASM 模块,确认已就绪。
- 将字体与已经带目录的示例文档
WithTOC.docx载入虚拟文件系统(VFS)。 - 创建
Document对象并载入该文档,取得第一节。 - 在正文末尾追加分页符、第五章标题与一段正文:标题应用 Heading 1 样式,正文沿用原文档的字体与字号。
- 调用
UpdateTableOfContents更新目录,新增章节的条目与页码随之写入。 - 用
SaveToFile保存结果,再从 VFS 读出文件触发下载。
更新已有目录页码的代码如下:
function App() {
const updateToc = async () => {
// 获取 Spire.Doc WASM 模块
const docModule = window.wasmModule?.spiredoc;
// 确保 WASM 模块完全加载完成
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
// 将字体与已经带目录的示例文档载入 VFS
await window.spire.FetchFileToVFS('msyh.ttc', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
await window.spire.FetchFileToVFS('msyhbd.ttc', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'WithTOC.docx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);
// 创建文档实例并载入已有文档
const doc = new docModule.Document();
doc.LoadFromFile({ fileName: inputFileName });
// 获取文档的第一节
const section = doc.Sections.get_Item(0);
// 在正文末尾追加一章:先分页,再写入标题与正文
const breakPara = section.AddParagraph();
breakPara.AppendBreak(docModule.BreakType.PageBreak);
const headingPara = section.AddParagraph();
headingPara.AppendText('第五章 后续计划');
headingPara.ApplyStyle({ builtinStyle: docModule.BuiltinStyle.Heading1 });
// 追加的正文沿用原文档的字体
const bodyFormat = new docModule.CharacterFormat(doc);
bodyFormat.FontName = '微软雅黑';
bodyFormat.FontSize = 10.5;
const bodyPara = section.AddParagraph();
bodyPara.AppendText('2027 年度计划把模板管理与权限审计纳入平台,并开放批量填写接口,供业务系统直接调用。').ApplyCharacterFormat(bodyFormat);
// 更新目录,新增章节的条目与页码据此写入
doc.UpdateTableOfContents();
// 定义输出文件名并保存
const outputFileName = '更新目录页码.docx';
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
// 释放资源
doc.Dispose();
// 从 VFS 读取生成的文件,触发下载
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>更新已有目录的页码</h1>
<button onClick={updateToc}>
更新目录
</button>
</div>
);
}
export default App;
更新已有目录的页码后,目录末尾新增「第五章 后续计划」一项,页码指向第 7 页,原有条目保持不变:

常见问题
添加的目录为什么出现在文档末尾
原因:AddParagraph 把新段落追加到所在节的末尾,直接在其上调用 AppendTOC 或加入 TableOfContent 对象,目录自然落在文末;已有文档的内容已经排好版,位置不会自己前移。
解决:先创建目录段落,再用 Paragraphs.Insert 把它移到目标位置:
const tocPara = section.AddParagraph();
tocPara.AppendTOC(1, 3);
section.Paragraphs.Insert(0, tocPara);
目录里为什么没有正文的标题
原因:目录按标题样式或大纲级别收集条目。原文档中的章节标题如果只是手动加粗、放大了字号,没有应用 Heading 1 至 Heading 3 等内置标题样式,更新后就找不到可收录的段落,目录可能为空,或只提示「未找到目录项」。
解决:载入文档后,对需要进入目录的段落调用 ApplyStyle 应用内置标题样式,再更新目录:
const headingPara = section.Paragraphs.get_Item(2);
headingPara.ApplyStyle({ builtinStyle: docModule.BuiltinStyle.Heading1 });
用 Paragraphs.Insert 指定索引后,目录位置和预期差了几段
原因:Paragraphs.Insert 的索引按正文中的子对象顺序计算,段落与表格各占一个位置。文档里的表格越多,同一段落在段落集合与正文对象中的位置差得越远,直接用段落集合的下标往往差几段。
解决:遍历 Body.ChildObjects 找到目标段落,把它的对象位置作为索引:
let insertIndex = 0;
const children = section.Body.ChildObjects;
for (let i = 0; i < children.Count; i++) {
const obj = children.get_Item(i);
if (obj.DocumentObjectType === docModule.DocumentObjectType.Paragraph && obj.StyleName === 'Heading1') {
insertIndex = i;
break;
}
}
目录页码与实际页面对不上
原因:目录页码在更新域时按当时的排版写入,之后如果继续增删正文或修改标题,目录不会自动同步;此外,在文档开头插入目录会让原有内容整体后移,页码也随之变化,这属于正常结果。
解决:在保存前再次调用 UpdateTableOfContents,让条目与页码按最新内容重新计算:
doc.UpdateTableOfContents();
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
自定义目录更新时报 ArgumentOutOfRange,或只显示一个 TOC 字样
原因:TableOfContent 加入段落后,如果缺少域分隔符、域结束标记,或没有赋给 Document.TOC,目录域就不完整:缺标记时页面可能只显示占位文字,缺绑定则更新时容易抛出索引越界异常。
解决:以下三步需要同时完成,再调用更新:
const toc = new docModule.TableOfContent(doc, '{\\o "1-2" \\h \\z \\u}');
const tocPara = section.AddParagraph();
tocPara.Items.Add(toc);
tocPara.AppendFieldMark(docModule.FieldMarkType.FieldSeparator);
tocPara.AppendText('TOC');
tocPara.AppendFieldMark(docModule.FieldMarkType.FieldEnd);
doc.TOC = toc;
获取免费许可证
如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。







