在 Excel 文档处理中,公式和函数是最核心的能力之一——无论是求和、求平均,还是日期与三角运算,公式都能让数据处理自动化、高效化。Spire.XLS for JavaScript 基于 WebAssembly 在浏览器端直接完成公式与函数的插入和读取,通过虚拟文件系统(VFS)管理输入输出文件,无需后端服务支持。
本文介绍两个核心功能点:
有关安装和项目配置,请参考 React 项目中集成 Spire.XLS for JavaScript。以下示例默认已安装 Spire.XLS 并完成 WebAssembly 模块初始化。
插入公式和函数到 Excel 工作表
Spire.XLS for JavaScript 提供的 Worksheet.Range.get() 方法返回的单元格 Range 对象的 Formula 属性可用于向 Excel 工作表中的指定单元格添加公式或函数。添加公式和函数到 Excel 工作表的主要操作步骤如下:
- 创建一个
Workbook的对象。 - 使用
Workbook.Worksheets.get()方法获取指定的工作表。 - 在单元格中写入数据并设置单元格格式。
- 使用
Range.Formula属性将公式和函数添加到工作表的指定单元格中。 - 使用
Workbook.SaveToFile()方法保存工作簿。
下面是一个完整的代码示例,展示了在 React 中向 Excel 工作表插入数学运算、日期函数、三角函数、平均值函数和求和函数:
function App() {
const insertFormulasAndFunctions = async () => {
// 获取 Spire.XLS WASM 模块
const xlsModule = window.wasmModule?.spirexls;
// 检查模块是否就绪
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// 将字体载入 VFS
await window.spire.FetchFileToVFS('simsun.ttc', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
// 创建 Workbook 对象
const workbook = new xlsModule.Workbook();
// 获取第一个工作表
const sheet = workbook.Worksheets.get(0);
// 声明两个变量:currentRow 和 currentFormula
let currentRow = 1;
let currentFormula = "";
// 设置列宽
sheet.SetColumnWidth(1, 32);
sheet.SetColumnWidth(2, 16);
// 在单元格中写入数据
sheet.Range.get({ row: currentRow, column: 1 }).Value = "测试数据";
sheet.Range.get({ row: currentRow, column: 2 }).NumberValue = 1;
sheet.Range.get({ row: currentRow, column: 3 }).NumberValue = 2;
sheet.Range.get({ row: currentRow, column: 4 }).NumberValue = 3;
sheet.Range.get({ row: currentRow, column: 5 }).NumberValue = 4;
sheet.Range.get({ row: currentRow, column: 6 }).NumberValue = 5;
currentRow += 2;
sheet.Range.get({ row: currentRow, column: 1 }).Value = "公式或函数";
sheet.Range.get({ row: currentRow, column: 2 }).Value = "结果";
// 设置单元格格式
let range = sheet.Range.get({ row: currentRow, column: 1, lastRow: currentRow, lastColumn: 2 });
range.Style.Font.FontName = "黑体";
range.Style.KnownColor = xlsModule.ExcelColors.LightGreen;
range.Style.FillPattern = xlsModule.ExcelPatternType.Solid;
range.Style.Borders.get(xlsModule.BordersLineType.EdgeBottom).LineStyle = xlsModule.LineStyleType.Medium;
range.Style.Font.IsBold = true;
// 数学运算
currentFormula = "=1/2+3*4";
currentRow += 1;
sheet.Range.get({ row: currentRow, column: 1 }).NumberFormat = "@";
sheet.Range.get({ row: currentRow, column: 1 }).Text = currentFormula;
sheet.Range.get({ row: currentRow, column: 2 }).Formula = currentFormula;
// 日期函数
currentFormula = "=TODAY()";
currentRow += 1;
sheet.Range.get({ row: currentRow, column: 1 }).NumberFormat = "@";
sheet.Range.get({ row: currentRow, column: 1 }).Text = currentFormula;
sheet.Range.get({ row: currentRow, column: 2 }).Formula = currentFormula;
sheet.Range.get({ row: currentRow, column: 2 }).Style.NumberFormat = "YYYY/MM/DD";
// 三角函数
currentFormula = "=SIN(PI()/6)";
currentRow += 1;
sheet.Range.get({ row: currentRow, column: 1 }).NumberFormat = "@";
sheet.Range.get({ row: currentRow, column: 1 }).Text = currentFormula;
sheet.Range.get({ row: currentRow, column: 2 }).Formula = currentFormula;
// 平均值函数
currentFormula = "=AVERAGE(B1:F1)";
currentRow += 1;
sheet.Range.get({ row: currentRow, column: 1 }).NumberFormat = "@";
sheet.Range.get({ row: currentRow, column: 1 }).Text = currentFormula;
sheet.Range.get({ row: currentRow, column: 2 }).Formula = currentFormula;
// 求和函数
currentFormula = "=SUM(B1:F1)";
currentRow += 1;
sheet.Range.get({ row: currentRow, column: 1 }).NumberFormat = "@";
sheet.Range.get({ row: currentRow, column: 1 }).Text = currentFormula;
sheet.Range.get({ row: currentRow, column: 2 }).Formula = currentFormula;
// 保存工作簿
const outputFileName = 'InsertFormulasAndFunctions_output.xlsx';
workbook.SaveToFile({ fileName: outputFileName, version: xlsModule.ExcelVersion.Version2010 });
// 释放资源
workbook.Dispose();
// 从 VFS 读取转换后的文件,触发下载
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
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>Insert Formulas and Functions</h1>
<button onClick={insertFormulasAndFunctions}>
Start
</button>
</div>
);
}
export default App;
插入公式和函数到 Excel 工作表结果

读取 Excel 工作表中的公式和函数
要读取 Excel 工作表中的公式和函数,需要循环遍历工作表中的所有已使用单元格,之后利用单元格的 HasFormula 属性找到包含公式或函数的单元格,然后用 Range.Formula 属性获取这些单元格中的公式或函数。详细操作步骤如下:
- 创建一个
Workbook的对象。 - 使用
Workbook.LoadFromFile()方法载入 Excel 工作簿。 - 使用
Workbook.Worksheets.get()方法获取第一个工作表。 - 循环浏览工作表中的已使用单元格。
- 使用
HasFormula属性检测一个单元格是否包含公式或函数。如果有,则使用Range.RangeAddressLocal属性和Range.Formula属性获取单元格名及其中的公式或函数,并输出获取的内容。
下面是一个完整的代码示例,展示了在 React 中遍历工作表并读取其中的公式和函数:
function App() {
const readFormulasAndFunctions = async () => {
// 获取 Spire.XLS WASM 模块
const xlsModule = window.wasmModule?.spirexls;
// 检查模块是否就绪
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// 将字体和 Excel 文件载入 VFS
await window.spire.FetchFileToVFS('simsun.ttc', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'FormulasAndFunctions.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);
// 创建 Workbook 对象
const workbook = new xlsModule.Workbook();
// 载入 Excel 工作簿
workbook.LoadFromFile({ fileName: inputFileName });
// 获取该工作簿的第一个工作表
const sheet = workbook.Worksheets.get(0);
// 获取该工作表已使用的单元格范围
const usedRange = sheet.AllocatedRange;
// 创建输出工作簿
const output = new xlsModule.Workbook();
const outSheet = output.Worksheets.get(0);
let outRow = 1;
// 循环遍历已使用的单元格
for (const cell of usedRange.Cells) {
// 判断单元格是否有公式或函数
if (cell.HasFormula) {
// 获取单元格名
const cellname = cell.RangeAddressLocal;
// 获取单元格中的公式或函数
const formula = cell.Formula;
// 写入读取到的单元格名和公式
outSheet.Range.get({ row: outRow, column: 1 }).Value = "单元格" + cellname + "包含:" + formula;
outRow += 1;
}
}
// 设置输出列宽,确保文本完整显示
outSheet.SetColumnWidth(1, 45);
// 保存输出工作簿
const outputFileName = 'ReadFormulasAndFunctions_output.xlsx';
output.SaveToFile({ fileName: outputFileName, version: xlsModule.ExcelVersion.Version2010 });
// 释放资源
output.Dispose();
// 从 VFS 读取转换后的文件,触发下载
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
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>Read Formulas and Functions</h1>
<button onClick={readFormulasAndFunctions}>
Start
</button>
</div>
);
}
export default App;
读取 Excel 工作表中的公式和函数结果

常见问题
HasFormula 检测不到公式,循环没有结果
原因:目标单元格中的公式实际是以文本形式写入的(用 Text/Value 属性而非 Formula 属性),HasFormula 只对真正的公式返回 true。
解决:插入时确认使用 Range.Formula 属性;否则读取前需先把文本重新赋值为公式。
Formula 与 FormulaNumberValue 属性混淆
原因:Formula 属性返回的是单元格中的公式字符串,而 FormulaNumberValue 属性返回的是公式计算后的数值结果,两者返回的内容不同。
解决:需要公式字符串时使用 cell.Formula,需要公式计算后的数值结果时使用 cell.FormulaNumberValue,根据实际需求选择对应的属性。
获取免费许可证
如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。







