Google DataTable visualization: calculating totals

I am looking for a way to add a row of summary data to a simple DataTable. This is my code:

// 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);

      

How to calculate myTotal

from dt

DataTable?

Can I make the last line (Total) bold?

Is there a more elegant way to add totals to a table?

+3


source to share


2 answers


create the following function:

function getSum(data, column) {
    var total = 0;
    for (i = 0; i < data.getNumberOfRows(); i++)
        total = total + data.getValue(i, column);
    return total;
}

      

call it with google generated datatable and column array index. In your case:



var total = getSum(dt,1);

      

Then you can add that total to the new raw or whatever you want to do with it.

0


source


As @ Danny's answer is the same solution as for summing a column, I won't write it.

To set a property of a cell, you dataTable.setProperty(columnIndex,rowIndex,'style','font-weight:bold;');

so in your case you should write dt.setProperty(0, 3, 'style','font-weight:bold;'); dt.setProperty(1, 3, 'style','font-weight:bold;');



Suppose you provided a bit more data, it might be awkward to type this for all cells, you can use a for loop like (to make the whole last line bold):

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

      

Unfortunately, you cannot set properties on an entire row / column (see the custom properties documentation for this).

0


source







All Articles