Google可视化数据表:计算总数

3
我正在寻找一种方法,在简单的DataTable中添加一行总计。这是我的代码:
// Create and populate the data table.
var dt = new google.visualization.DataTable();

dt.addColumn('string', 'Name');
dt.addColumn('number', 'Height');

dt.addRows([
    ['Tong Ning mu', 174],
    ['Huang Ang fa', 523],
    ['Teng nu', 86]
]);

var myTotal;
/* calculate total sum of column Height */
dt.addRow(['TOTAL', myTotal]);

// Create and draw the visualization.
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(dt, null);

如何从dt DataTable计算myTotal

能否将最后一行(合计)加粗?

是否有更优雅的方法向表格添加合计?

2个回答

1
创建以下函数:
function getSum(data, column) {
    var total = 0;
    for (i = 0; i < data.getNumberOfRows(); i++)
        total = total + data.getValue(i, column);
    return total;
}

使用您创建的Google数据表和列数组索引调用它。在您的情况下:

var total = getSum(dt,1);

然后,您可以将该总数添加到新的行中或者按您的需求进行操作。

0

由于@Danny的回复与我所说的对于列求和的解决方案相同,因此我不会写它。

要设置单元格属性,您可以使用dataTable.setProperty(columnIndex,rowIndex,'style','font-weight:bold;');

因此,在您的情况下,您将编写
dt.setProperty(0, 3, 'style','font-weight:bold;'); dt.setProperty(1, 3, 'style','font-weight:bold;');

假设您提供了一个稍大的数据表,为所有单元格键入这些内容可能会很麻烦,您可以使用for循环(使整个最后一行变粗):

var lastRow = dt.getNumberOfRows()-1
for (i=0, n=dt.getNumberOfColumns(); i < n; i++) {
   dt.setProperty(i, lastRow, 'style', 'font-weight:bold;');
}

很遗憾,您无法为整个行/列设置属性(有关此事,请参阅文档中有关自定义属性的内容)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接