Excel 公式引擎(HyperFormula)
灵感:能力工具箱 excel-formula(pkg: hyperformula)。
在浏览器里用 Excel 风格公式算报价/分成表,无需打开桌面 Excel,也不把整表丢到后端算。
何时使用
- 报价明细:数量 × 单价、合计、折扣
- 分成试算:
=A1*0.2一类规则 - 需要与 Excel 公式习惯对齐的前端计算
硬约束
- 依赖
hyperformula;计算在本地完成。 - 公式字符串来自可信配置或校验后的模板;对用户输入做长度/字符集约束。
- 错误单元格返回可读中文提示(如
#DIV/0!→「除零」),勿裸抛。 - 金额展示可与
currency.jsSkill 配合,本包专注公式求值。 - 实现要点可标 小四原创。
实现要点(小四原创)
import { HyperFormula } from 'hyperformula'
// 小四原创:一张小表跑 Excel 公式
export function evalQuoteSheet(rows: (string | number)[][]) {
const hf = HyperFormula.buildFromArray(rows, { licenseKey: 'gpl-v3' })
const sheetId = 0
const height = rows.length
const width = Math.max(...rows.map((r) => r.length), 0)
const values: (string | number | boolean)[][] = []
for (let r = 0; r < height; r++) {
const line: (string | number | boolean)[] = []
for (let c = 0; c < width; c++) {
const v = hf.getCellValue({ sheet: sheetId, row: r, col: c })
line.push(typeof v === 'object' && v && 'type' in (v as object) ? '#ERR' : (v as any))
}
values.push(line)
}
return { values, destroy: () => hf.destroy() }
}
// 例:[['数量','单价','金额'],[2,99.9,'=A2*B2']]
Agent 步骤
- 安装
hyperformula,封装evalQuoteSheet。 - 自测:
=SUM、乘积、百分比;坏公式有中文/友好错误。 - UI:表格编辑单元格后重算;注意销毁实例。
附加
- README.md · templates/usage.md