本文最后更新于 2024-12-05T18:40:20+08:00
1. element ui 默认合计功能
官方文档是这样演示的,需要添加 show-summary :summary-method=”getSummaries”
1 2 3 4 5 6 7 8
| <el-table :data="tableData" border height="200" :summary-method="getSummaries" show-summary style="width: 100%; margin-top: 20px"> </el-table>
|
getSummaries方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| getSummaries(param) { const { columns, data } = param; const sums = []; columns.forEach((column, index) => { if (index === 0) { sums[index] = '总价'; return; } const values = data.map(item => Number(item[column.property])); if (!values.every(value => isNaN(value))) { sums[index] = values.reduce((prev, curr) => { const value = Number(curr); if (!isNaN(value)) { return prev + curr; } else { return prev; } }, 0); sums[index] += ' 元'; } else { sums[index] = 'N/A'; } });
return sums; } }
|
有个需求与如上类似,但是最后一行有几列是需要百分百比计算的,原本的只是单纯对每一列求和而已,所以需要修改一下getSummaries 方法之前的都不变,最后添加上如上两行,如果是动态的数据,column.property可以得到具体的列的title,然后再处理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| getSummaries(param) { const {columns, data} = param const sums = [] columns.forEach((column, index) => { if (index === 0) { sums[index] = 'Sum' return } const values = data.map(item => Number(item[column.property])) if (!values.every(value => isNaN(value))) { const totalSum = values.reduce((prev, curr) => { const value = Number(curr) if (!isNaN(value)) { return prev + curr } else { return prev } }, 0) sums[index] = totalSum.toFixed(2) + ' ' } else { sums[index] = 'N/A' } }) sums[6] = ((Number.parseFloat(sums[3]) - Number.parseFloat(sums[1])) / Number.parseFloat(sums[3]) * 100).toFixed(2) + '%' sums[7] = ((Number.parseFloat(sums[4]) - Number.parseFloat(sums[2])) / Number.parseFloat(sums[4]) * 100).toFixed(2) + '%' return sums }
|
2. 下载表格数据
2.1 需要安装这两个包
1
| npm install json2csv file-saver --save
|
2.2 添加一个按钮
1
| <el-button type="primary" icon="el-icon-download" @click="downloadCSV">Download</el-button>
|
2.3 下载的方法
1 2 3 4 5 6 7
| downloadCSV() { const csvData = json2csv.parse(this.allData) const blob = new Blob([csvData], {type: 'text/csv;charset=utf-8;'}) saveAs(blob, 'white-app_id_report.csv') }
|