Handsontable中父项工时求和:实现年度总工时统计
在Handsontable中实现父项工时的全年总计
你需要在现有columnSummary逻辑基础上,添加对全年总计行的处理,仅针对所有月份父项的total_hours进行求和,以下是具体实现:
修改后的核心逻辑
在columnSummary函数末尾添加全年总计的求和规则:
// 添加全年总计的求和规则 const totalRow = nestedRowsCache.levels[0].find(item => item.month === 'Year Total'); if (totalRow) { // 筛选出所有带子项的父行(排除总计行) const parentRows = nestedRowsCache.levels[0].filter(item => item.__children && item.__children.length > 0 && item.month !== 'Year Total' ); const totalEndpoint = { destinationColumn: resultColumn, destinationRow: getRowIndex(totalRow), type: 'sum', forceNumeric: true, ranges: [] }; // 把每个父项的total_hours单元格加入求和范围 parentRows.forEach(row => { totalEndpoint.ranges.push([getRowIndex(row), getRowIndex(row)]); }); endpoints.push(totalEndpoint); }
完整的columnSummary函数
columnSummary() { const endpoints = []; const nestedRowsPlugin = this.hot.getPlugin('nestedRows'); const getRowIndex = nestedRowsPlugin.dataManager.getRowIndex.bind(nestedRowsPlugin.dataManager); const resultColumn = 3; let tempEndpoint = null; let nestedRowsCache = null; if (nestedRowsPlugin.isEnabled()) { nestedRowsCache = this.hot.getPlugin('nestedRows').dataManager.cache; } else { return; } // 生成每月父项的子项求和规则 for (let i = 0; i < nestedRowsCache.levels[0].length; i++) { tempEndpoint = {}; if (!nestedRowsCache.levels[0][i].__children || nestedRowsCache.levels[0][i].__children.length === 0) { continue; } tempEndpoint.destinationColumn = resultColumn; tempEndpoint.destinationRow = getRowIndex(nestedRowsCache.levels[0][i]); tempEndpoint.type = 'sum'; tempEndpoint.forceNumeric = true; tempEndpoint.ranges = []; tempEndpoint.ranges.push([ getRowIndex(nestedRowsCache.levels[0][i].__children[0]), getRowIndex(nestedRowsCache.levels[0][i].__children[nestedRowsCache.levels[0][i].__children.length - 1]) ]); endpoints.push(tempEndpoint); tempEndpoint = null; } // 添加全年总计的求和规则 const totalRow = nestedRowsCache.levels[0].find(item => item.month === 'Year Total'); if (totalRow) { const parentRows = nestedRowsCache.levels[0].filter(item => item.__children && item.__children.length > 0 && item.month !== 'Year Total' ); const totalEndpoint = { destinationColumn: resultColumn, destinationRow: getRowIndex(totalRow), type: 'sum', forceNumeric: true, ranges: [] }; parentRows.forEach(row => { totalEndpoint.ranges.push([getRowIndex(row), getRowIndex(row)]); }); endpoints.push(totalEndpoint); } return endpoints; },
效果说明
- 原有逻辑保持不变:每月父项的
total_hours仍会自动求和其子项的工时。 - 新增逻辑:最后一行的"Year Total"会自动计算所有月份父项的工时总和,完全符合仅对父项数据求和的需求。
内容的提问来源于stack exchange,提问作者Mohammad
相关产品推荐
相关产品推荐

