himanshu
Here is an example how I calculate and display column totals for a grid that is generated by a SP.
const grid = widget;
const instrumentNames = "<<Session.InstrumentNames>>"; // This contains the column labels, concatenated by '|' (pipe character)`
// Attach Kendo grid event handlers
grid.bind("dataBound", onDataBound);
// Object numberColumns contains information about the number columns in the table and the functions to update and display the totals for each column.
// This code assumes that number columns (as generated by the SP) are named C01, C02, C03 etc.
const numberColumns = {
numberOfColumns: 0,
colFields: [],
formats: [],
totals: [],
overallTotal: 0,
isInitialised: false,
initialise: function (instrumentNames) {
// create array with column fields for the pivot table columns (C01, C02, C03 etc)
let count = 0;
instrumentNames.split("|").forEach(() => {
count++;
numberColumns.colFields[count - 1] = "C" + count.toString().padStart(2, "0");
});
this.numberOfColumns = count;
this.totals.length = count;`
// create array with formats for the number columns
for (let i = 0; i < this.numberOfColumns; i++) {
let gridColumn = grid.columns.find((x) => x.field === this.colFields[i]);
this.formats[i] = gridColumn ? gridColumn.format : "";
}
},
// Calculate the totals for each column and visible row in the grid
calculateTotals: function () {
this.totals.fill(0);
grid.tbody.find("tr").each(function () {
let dataItem = grid.dataItem(this);
if (dataItem) {
for (let i = 0; i < numberColumns.numberOfColumns; i++) {
numberColumns.totals[i] += Number(
dataItem[numberColumns.colFields[i]]
);
}
}
});`
` this.overallTotal = this.totals.reduce(
(accumulator, currentValue) => accumulator + currentValue
);
},
displayTotals: function () {
// put the (sub)totals for each column as formatted string in an array
let totalString = this.totals.map((x) => kendo.toString(x, "#,##0"));
// display the (sub)totals and possibly grand totals at the bottom cell of each column
// this assumes that these HTML cells have an ID equal to EP_[datafield], e.g. EP_C01. This ID must be set in the template of the grid (column settings) `
` for (let i = 0; i < this.numberOfColumns; i++) {
grid.footer.find("div#EP_" + this.colFields[i])
.children()
.html(totalString[i]);
}
},
};
// Handles the data bound event.
// This function is called when the grid has been bound to the data.
function onDataBound(e) {
if (!numberColumns.isInitialised) {
numberColumns.initialise(instrumentNames);
numberColumns.isInitialised = true;
}
numberColumns.calculateTotals();
numberColumns.displayTotals();
}