Excel中用户选择区域时可以在下方看到选择数据的统计,本示例演示如何在SpreadJS中实现选择区域改变时实时数据统计。
实现这个功能的核心就是在SelectionChanging事件中,获取选中区域的数据,进行统计,下面直接看下代码。
activeSheet.bind(GcSpread.Sheets.Events.SelectionChanging, function (e, info) {
var sheet = info.sheet;
var selections = info.newSelections; //得到新选择区域var totalCount = 0, numCount = 0, total = 0; //统计数据初始值if(selections && selections.length){for(var i = 0; i < selections.length; i++){var selection = selections[i];
for(var row = selection.row; row < selection.row + selection.rowCount; row++){for(var col = selection.col; col < selection.col + selection.colCount; col++){var value = sheet.getValue(row, col);
if(value !== null && value !== undefined && value !== ""){if(isFinite(value)){numCount++; //统计Number数量
total += value; //求和
}totalCount ++; //统计非空数据数量
}}}}if(totalCount>0){
var text = "计数:"+totalCount + (numCount > 0 ? " 平均值:" + total/numCount +" 求和:" + total : "");$("#sumInfo").html(text);
}else{
$("#sumInfo").html("");
}}else{
$("#sumInfo").html("")
}});
在SelectionChanging事件中我们可以从info中获取到sheet,sheetName,oldSelections以及newSelections四个参数。newSelections就是当前最新的选择区域,我们循环获取该区域内的数据,就可以到我们想要的数据统计了。
改示例的在现在演示可以在RunJS看到,地址:http://runjs.cn/detail/uxlmtnos
更多资源
SpreadJS中文学习指南:http://demo.grapecity.com.cn/SpreadJS/TutorialSample/#/samples
SpreadJS在线英文产品文档:http://sphelp.grapecity.com/webhelp/SpreadJSWeb/webframe.html#welcome.html
如果您对SpreadJS产品感兴趣,可以到官方网站下载试用:/developer/spreadjs
如果你有疑问,可以到GCDN论坛获得技术支持:http://gcdn.grapecity.com.cn