首先要明确是否是自动合并,其次是全部合并还是仅上下或仅左右,一般都是上下合并
举个例子(这里只做了上下合并):
整个标记结构数据,记录行、列、合并几个单元格。**最后一条数据也记得处理!!!**最后将标记数据处理成handsontable需要的数据格式
const list = []
const obj = {
col: 0, // 哪一行
cols: [
{
value: '', // 对比内容
row: 0, // 从那一列开始
rowspan: 0, // 合并几个
colspan: 1 // 0
}
]
}
let rowspan = 1
this.hotSettings.columns.forEach((item, index) => { // 每一列的key
list.push(JSON.parse(JSON.stringify(obj)))
list[index].col = index
data.forEach((v, i) => {
if (v[item.data] === list[index].cols[list[index].cols.length - 1].value && (data.length - 1 === i)) {
rowspan = rowspan + 1
if (rowspan > 1) {
list[index].cols[list[index].cols.length - 1].row = (i - rowspan) < 0 ? 0 : i - rowspan
list[index].cols[list[index].cols.length - 1].rowspan = rowspan
list[index].cols.push(JSON.parse(JSON.stringify(obj.cols[0])))
rowspan = 1
}
} else if (v[item.data] === list[index].cols[list[index].cols.length - 1].value) {
rowspan = rowspan + 1
}
if (v[item.data] !== list[index].cols[list[index].cols.length - 1].value) {
if (rowspan > 1) {
list[index].cols[list[index].cols.length - 1].row = i - rowspan
list[index].cols[list[index].cols.length - 1].rowspan = rowspan
list[index].cols.push(JSON.parse(JSON.stringify(obj.cols[0])))
rowspan = 1
}
list[index].cols[list[index].cols.length - 1].value = v[item.data]
}
})
})
const mergeData = []
list.forEach(item => {
item.cols.forEach(v => {
if (v.rowspan > 0) {
mergeData.push({ row: v.row, col: item.col, rowspan: v.rowspan, colspan: v.colspan })
}
})
})
思路有了,简单的代码也有了,接下来简化一下
稍稍有点不一样的地方就是,这里是直接拿第一个单元格的内容然后一直向下比较
const data =this.$refs.hot.hotInstance.getData()
const mergeCells = []
this.autoMergeColumns.forEach(col => {
let value = data[0][col]
let mergeCell = {
row: 0,
col: col,
rowspan: 1,
colspan: 1
}
for (let i = 1; i < data.length; i++) {
if (value !== null && value !== undefined && data[i][col] === value) {
mergeCell.rowspan++
if (i === data.length - 1 && mergeCell.rowspan > 1) {
mergeCells.push(mergeCell)
}
} else {
if (mergeCell.rowspan > 1) {
mergeCells.push(mergeCell)
}
value = data[i][col]
mergeCell = {
row: i,
col: col,
rowspan: 1,
colspan: 1
}
}
}
})