如何使用Javascript解析html表格单元格的公式,使其像Excel一样工作

How to parse formula of html table cell to acting like Excel, using Javascript

本文关键字:Excel 工作 一样 html 解析 Javascript 何使用 表格 单元格      更新时间:2023-09-26

我正在寻找一种使用Javascript使html表像excel一样工作的方法(首选Jquery)。这是我的问题。我做了这样一张桌子:

 <table>
       <tr>
          <td id="A1">10</td>
          <td id="B1">10.5</td>
       </tr>
       <tr>
          <td id="A2">5</td>
          <td id="B2" formula="A1+B1+A2"></td>
       </tr>
 </table>

每个 td 都有一个 id,其中一些 tds 添加了公式属性。我想计算这些公式,将公式的值给出 td。

在上表中,我想分配 B2 值 25.5(B2=A1+B1+A2)。

看起来像这样:

<td id="B2" formula="A1+B1+A2">25.5</td>

谁能给我一个线索?谢谢。

PS:这是我找到的一些资源,但它们不能解决我的问题

  1. DOM 上类似电子表格的公式

  2. http://zaach.github.com/jison/docs/


非常感谢@palindrom。我终于根据你的回答解决了我的问题。

这是我的代码:

    $("td[formula]").each(function(){
        //1 get formula attribute
        var formula = $(this).attr('formula');
        //2 use regex to make expression, with the surpport of "A122", "AB1" and more
        var expression = formula.replace(/([A-Z]+[0-9]+)/g, "parseFloat('$('#$1').html())") ;
        //3 eval the expression
        var result = eval( expression );
        //4 set the value
        $(this).html(result);
     });
应该

适用于简单的数学,没有尝试:

$("td[formula]").each( function() {
  this.html( eval( this.attr("formula").replace(/[a-z][0-9]/g, "'$('#$0').html()") ) );
} );

编辑:如果你在公式中有像 sum 这样的函数,将它们实现为 javascript 函数,它们也应该可以工作。

即使为时已晚,也可以尝试使用此插件 https://github.com/xsanisty/jquery-calx

我在其核心中使用 jison 解析器开发了它,它将像您想要的那样解析数据公式属性中的公式

这是我

写的一个html表格,其中为每一行计算了一个公式(参见iframe源代码)。
该公式是用 JavaScript 编写的(尽可能复杂),其中 [abc] 替换为 id=abc(标题中的权重)的单元格值,{abc} 替换为该行中同一列的单元格中的文本。
列是可排序的
权重可由用户修改,并被记住在 cookie 中。

希望这能有所帮助。