我的单元格统计了后续单元格的值之和,我插入了公式,查询论坛发现富文本和公式不能同事使用,我想在汇总的值前插入'Total:'字符,下面代码虽然可以拼接了,但是汇总公式失效了- export function insertGeneralFormula(sheet: GC.Spread.Sheets.Worksheet, spread) {
- const colCount = sheet.getColumnCount() // 获取总列数
- const targetRow = 1 // 目标行,第二行(从 0 开始)
- const startCol = 2 // 从第三列开始(从 0 开始)
- // 构造汇总公式:从第三列开始的所有列
- let formula = ''
- for (let col = startCol; col < colCount; col++) {
- const colLetter = String.fromCharCode(65 + col) // 获取列字母(A, B, C, D, ...)
- formula += formula ? `+${colLetter}${targetRow + 1}` : `${colLetter}${targetRow + 1}`
- }
- // 1. 在第二行第二列插入公式
- sheet.setFormula(targetRow, 1, `=${formula}`)
- // 强制刷新并等待公式计算完成
- // 使用 spread.getActiveSheet().getValue 以确保获取公式计算后的值
- const totalValue = sheet.getValue(targetRow, 1)
- // 格式化数字
- applyNumberFormatter(sheet, targetRow, 1, totalValue)
- // 3. 确保注册自定义函数
- registerRichTextFunction(spread)
- // 4. 在公式中插入富文本
- sheet.setFormula(1, 1, `=RICHTEXT("${totalValue.toString()}")`) // 确保值是字符串
- }
- // 定义自定义函数 RichTextFunction
- function registerRichTextFunction(spread) {
- // 定义 RichTextFunction
- class RichTextFunction extends GC.Spread.CalcEngine.Functions.Function {
- constructor() {
- super('RICHTEXT', 1, 9999999) // 名称为 "RICHTEXT",最少 1 个参数,最多无限多个参数
- }
- evaluate(args) {
- const inputText = args[0] // 获取第一个参数的值
- console.log('inputText', inputText)
- if (!inputText) {
- return { richText: [] } // 如果没有传入值,返回空的富文本
- }
- // 构造富文本 JSON
- const richText = [
- {
- style: {
- font: 'bold 14px "Microsoft YaHei"', // 加粗、14px 字体
- foreColor: 'rgb(255, 0, 0)', // 红色
- textDecoration: 0,
- },
- text: 'Total: ', // 前缀文本
- },
- {
- style: {
- font: '14px "Microsoft YaHei"', // 普通字体、14px
- foreColor: 'rgb(0, 0, 0)', // 黑色
- textDecoration: 0,
- },
- text: inputText, // 确保动态插入的值是字符串
- },
- ]
- return { richText } // 返回富文本对象
- }
- }
- // 注册自定义函数
- const richTextFunction = new RichTextFunction()
- // 注意:确保每次都重新注册自定义函数
- spread.getActiveSheet().addCustomFunction(richTextFunction)
- }
复制代码
|