如何在MUI Data Grid中添加汇总行?
MUI DataGrid 添加汇总行实现方案
实现思路
- 计算汇总数据:提取表格
Amount列的数值,求和后格式化为统一的货币样式 - 自定义表格底部:利用MUI DataGrid的
slotProps.footer属性,插入与表格列对齐的汇总行,保持样式与表格主体一致
代码修改示例
import React from 'react'; import { DataGrid } from '@mui/x-data-grid'; import './Invoice.scss'; const Invoice = () => { const rows = [ { id: 1, col1: '1', col2: '', col3: 'Power Sweeping1', col4: '', col5: '1', col6: '$1.350,00', col7: '$1.350,00' }, { id: 2, col1: '2', col2: '', col3: 'Power Sweeping2', col4: '', col5: '1', col6: '$1.350,00', col7: '$1.350,00' }, { id: 3, col1: '3', col2: '', col3: 'Power Sweeping3', col4: '', col5: '1', col6: '$1.350,00', col7: '$1.350,00' }, ]; const columns = [ { field: 'col1', headerName: '#', width: 10 }, { field: 'col2', headerName: 'Date', width: 150 }, { field: 'col3', headerName: 'Product or service', width: 250 }, { field: 'col4', headerName: 'SKU', width: 150 }, { field: 'col5', headerName: 'Qty', width: 150 }, { field: 'col6', headerName: 'Rate', width: 150 }, { field: 'col7', headerName: 'Amount', width: 150 }, ]; // 计算Amount列总和并格式化 const calculateTotal = () => { let total = 0; rows.forEach(row => { // 解析货币格式为数字 const amount = parseFloat(row.col7.replace(/[$.]/g, '').replace(',', '.')); total += amount; }); // 转回目标货币格式 return `$${total.toFixed(2).replace('.', ',')}`; }; const totalAmount = calculateTotal(); return ( <div className="container"> <h1>Invoice</h1> <div id='table' className='row'> <div style={{ height: 300, width: '100%' }}> <DataGrid rows={rows} columns={columns} hideFooterPagination={true} hideFooterSelectedRowCount={true} // 自定义底部汇总行 slotProps={{ footer: () => ( <div style={{ display: 'flex', alignItems: 'center', height: '52px', padding: '0 16px', borderTop: '1px solid rgba(224, 224, 224, 1)', fontWeight: 'bold' }}> <div style={{ width: '10px' }}></div> <div style={{ width: '150px' }}></div> <div style={{ width: '250px', textAlign: 'right', paddingRight: '16px' }}>Total:</div> <div style={{ width: '150px' }}></div> <div style={{ width: '150px' }}></div> <div style={{ width: '150px' }}></div> <div style={{ width: '150px' }}>{totalAmount}</div> </div> ) }} /> </div> </div> </div> ); }; export default Invoice;
关键说明
- 修正了原代码中
rows的id重复问题(DataGrid要求每行id唯一) - 货币格式处理:通过正则转换字符串为数字计算总和,再转回要求的格式
- 汇总行宽度与表格列一一对应,确保对齐;添加顶部边框和加粗字体,匹配示例效果
- 借助
slotProps.footer自定义底部区域,汇总行固定在表格底部,不与数据行混淆
内容的提问来源于stack exchange,提问作者Willians Martins
相关产品推荐
相关产品推荐

