项目场景:
前端开发往往会遇到表格处理的问题,例如合并单元格,该文章给处理自动合并单元格的方法
问题:
例如我们想把下面的表格做出合并:
班级 | 姓名 | 班主任 | 语文 | 数学 |
高三(1) | 张三 | 郝老师 | 89 | 89 |
高三(1) | 王五 | 郝老师 | 89 | 89 |
高三(2) | 李四 | 张老师 | 89 | 89 |
高三(2) | 小敏 | 张老师 | 89 | 89 |
高三(1) | 小米 | 郝老师 | 89 | 89 |
得到如下的表格样式:
班级 | 姓名 | 班主任 | 语文 | 数学 |
高三(1) | 张三 | 郝老师 | 89 | 89 |
王五 | 89 | 89 | ||
高三(2) | 李四 | 张老师 | 89 | 89 |
小敏 | 89 | 89 | ||
高三(1) | 小米 | 郝老师 | 89 | 89 |
解决方案:
const data = [
{
class:'高三(1)',
name:'张三',
teacher:'郝老师',
chinese:'89',
mathematics:'89',
},
{
class:'高三(1)',
name:'王五',
teacher:'郝老师',
chinese:'89',
mathematics:'89',
},
{
class:'高三(2)',
name:'李四',
teacher:'张老师',
chinese:'89',
mathematics:'89',
},
{
class:'高三(2)',
name:'小敏',
teacher:'张老师',
chinese:'89',
mathematics:'89',
},
{
class:'高三(1)',
name:'小米',
teacher:'郝老师',
chinese:'89',
mathematics:'89',
},
]
const columns = [
{
title: '班级',
dataIndex: 'class',
key: 'class',
render: (text, record, index) => {
const obj = {
children: text !== null ? text : '',
props: {}
}
obj.props.rowSpan = mergeCells(text, data,'class', index)//对班级合并,则传班级的字段作为key值
return obj
},
},
{
title: '姓名',
dataIndex: 'name',
key: 'name',
},
{
title: '班主任',
dataIndex: 'teacher',
key: 'teacher',
render: (text, record, index) => {
const obj = {
children: text !== null ? text : '',
props: {}
}
obj.props.rowSpan = mergeCells(text, data,'teacher', index)//对班主任合并,则传班主任的字段作为key值
return obj
},
},
{
title: '语文',
dataIndex: 'chinese',
key: 'chinese',
},
{
title: '数学',
dataIndex: 'mathematics',
key: 'mathematics',
},
];
const mergeCells = (text, data, key, index) => {
// 上一行该列数据是否一样
if (index !== 0 && text === data[index - 1][key]) {
return 0
}
let rowSpan = 1
// 判断下一行是否相等
for (let i = index + 1; i < data.length; i++) {
if (text !== data[i][key]) {
break
}
rowSpan++
}
return rowSpan
}