Word 文档变量(DocVariable)是一种轻量级的字段机制,允许在文档中定义占位符,并通过代码动态填充或更新内容。这种机制在模板化文档生成、批量信函制作和自动化报表输出等场景中非常实用。Spire.Doc for JavaScript 基于 WebAssembly 在浏览器端直接完成变量的全部操作,通过虚拟文件系统(VFS)管理输入输出文件,无需后端服务支持。
本文介绍三个核心功能点:
有关安装和项目配置,请参考 React 项目中集成 Spire.Doc for JavaScript。以下示例默认已安装 Spire.Doc 并完成 WebAssembly 模块初始化。
添加文档变量
添加文档变量的核心流程分为三个阶段:首先通过 FetchFileToVFS 将字体文件载入 WASM 虚拟文件系统;然后实例化 Document,在段落中插入 DocVariable 域字段,并通过 Variables.Add 方法为变量赋值;最后保存文档并从 VFS 读取生成的文件,封装为 Blob 后触发浏览器下载。
import React from 'react';
function App() {
const addVariables = async () => {
// 获取 Spire.Doc WASM 模块
const docModule = window.wasmModule?.spiredoc;
// 检查模块是否就绪
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
// 创建文档对象
const doc = new docModule.Document();
// 添加一个节
const section = doc.AddSection();
// 添加一个段落
const paragraph = section.AddParagraph();
// 在段落中插入一个 DocVariable 域字段
paragraph.AppendField("A1", docModule.FieldType.FieldDocVariable);
// 为 DocVariable 域字段对应的变量赋值
doc.Variables.Add("A1", "12");
// 更新域以显示变量值
doc.IsUpdateFields = true;
// 定义输出文件名
const outputFileName = "AddVariables_out.docx";
// 保存文档
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
// 释放资源
doc.Dispose();
const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([modifiedFileArray], { 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={addVariables}>
Generate
</button>
</div>
);
};
export default App;
通过 Variables.Add 方法添加变量后,文档中的 DocVariable 域字段会被替换为对应的变量值。

检索文档变量
对于已包含变量的 Word 模板文档,可以通过索引或变量名称检索变量信息。Spire.Doc 提供了多种检索方式:通过索引获取变量名称和值,或直接通过变量名获取对应的值。
import React from 'react';
function App() {
const retrieveVariables = async () => {
// 获取 Spire.Doc WASM 模块
const docModule = window.wasmModule?.spiredoc;
// 检查模块是否就绪
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
const inputFileName = 'Template_Docx_6.docx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);
// 加载文档
const doc = new docModule.Document();
doc.LoadFromFile(inputFileName);
// 通过索引获取变量名称和值
const nameByIndex = doc.Variables.GetNameByIndex(0);
const valueByIndex = doc.Variables.GetValueByIndex(0);
// 通过变量名直接获取值
const valueByName = doc.Variables.get_Item("A1");
// 遍历所有变量
let stringBuilder = [];
stringBuilder.push("This document has following variables:\n");
for (let i = 0; i < doc.Variables.Count; i++) {
let name = doc.Variables.GetNameByIndex(i);
let value = doc.Variables.GetValueByIndex(i);
stringBuilder.push("Name: " + name + ", " + "Value: " + value + "\n");
}
// 将结果写入文本文件
const outputFileName = "RetrieveVariables_out.txt";
window.dotnetRuntime.Module.FS.writeFile(outputFileName, stringBuilder.join(""));
// 从 VFS 读取生成的文件,触发下载
const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([modifiedFileArray], { type: 'text/plain' });
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={retrieveVariables}>
Generate
</button>
</div>
);
}
export default App;
检索结果以文本文件输出,清晰列出文档中所有变量的名称及对应的值。

移除文档变量
当模板文档中存在不再需要的变量时,可以通过 Variables.Remove 方法按变量名称将其移除。移除后配合 IsUpdateFields 属性更新域,确保生成的文档干净无冗余。
function App() {
const removeVariables = async () => {
// 获取 Spire.Doc WASM 模块
const docModule = window.wasmModule?.spiredoc;
// 检查模块是否就绪
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
const inputFileName = 'Template_Docx_6.docx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);
// 加载文档
const doc = new docModule.Document();
doc.LoadFromFile(inputFileName);
// 按变量名称移除变量
doc.Variables.Remove("A1");
let name = doc.Variables.GetNameByIndex(0);
doc.Variables.Remove(name);
doc.Variables.Remove(doc.Variables.GetNameByIndex(0));
doc.IsUpdateFields = true;
// 定义输出文件名
const outputFileName = "RemoveVariables_out.docx";
// 保存文档
doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013 });
// 从 VFS 读取生成的文件,触发下载
const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([modifiedFileArray], { 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={removeVariables}>
Generate
</button>
</div>
);
}
export default App;
移除变量后生成的文档中,目标变量及其对应的 DocVariable 域字段将被清除,文档内容更加简洁。

常见问题
添加变量后文档中仍显示域代码而非实际值
原因:DocVariable 域字段创建后,默认不会自动更新显示变量值。如果未设置 IsUpdateFields 属性,文档中会保留域代码文本。
解决:保存文档前将 IsUpdateFields 属性设置为 true:
document.IsUpdateFields = true;
按名称获取变量值时返回空
原因:传入的变量名称大小写或拼写与文档中实际定义的变量名不一致,导致匹配失败。
解决:先通过遍历 document.Variables 集合,使用 GetNameByIndex 方法确认文档中实际的变量名称,再按准确名称获取值:
for (let i = 0; i < document.Variables.Count; i++) {
let name = document.Variables.GetNameByIndex(i);
let value = document.Variables.GetValueByIndex(i);
console.log("Name: " + name + ", Value: " + value);
}
获取免费许可证
如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。







