Search code examples
handsontable

Handsontable cross calculations


I have a handontable demo.

document.addEventListener("DOMContentLoaded", function() {

  var
    example = document.getElementById('example1'),
    hot1;

  hot1 = new Handsontable(example, {
    data: [
        ['', '', '', ''],
        [1, 2, 3, '=SUM(A2:C2)'],
      [1, 2, 3],
    ],
    width: 584,
    height: 320,
    rowHeaders: true,
    formulas: true,
    colHeaders: true,
    columns: [1, 2, 3, 4],
    columnSummary: function () {
        var summary = [];
        for (var i = 0; i < 4; i++) {
        summary.push({
            ranges: [[1, 2]],
          destinationRow: 0,
          destinationColumn: i,
          type: 'sum',
          forceNumeric: true,
          sourceColumn: i
        });         
      }

      return summary;
    }
  });

});

It caclulates:

  • Sum of column and puts a result in the first raw.
  • Sum of rows (except first one) and puts it in the column "D"

I need to calculate correct total of the totals, which is the cell D1. After loading and changing any cell calculation of D1 has to work properly.

Thank you for any ideas.


Solution

  • The option columnSummary should not be applied on the 4th column (the column of SUM results). Try to apply you code of columnSummary option only for the first three columns :

    for (var i = 0; i < 3; i++) //Instead of i < 4
    

    And use in the row one what you use to calculate the sum on your other rows :

    data: [
        ['', '', '', '=SUM(A1:C1)'],
        [1, 2, 3, '=SUM(A2:C2)'],
        [1, 2, 3, '=SUM(A3:C3)'],
    ],
    

    You will see that it works like a charm : JSFiddle.