废话不多说,先上demo代码
<template>
<div class="excel-box">
<table class="excel-table" style="" border="1" >
<thead>
<!--此处只自动合并了第一列即item.company。-->
<tr v-for="(item,index) in testData">
<th :rowspan="item.companyspan" :class="{hidden: item.companydis}" style=" vertical-align:none;" >{{item.company}}</th>
<th>{{item.powerName}}</th>
<th>{{item.thisPeriod}}</th>
<th>{{item.theSamePeriod}}</th>
<th>{{item.yearOnYear}}</th>
<th>{{item.thisYearTotal}}</th>
<th>{{item.theSamePeriodTotal}}</th>
<th>{{item.totalYearOnYear}}</th>
</tr>
</thead>
</table>
</div>
</template>
<style scoped>
.hidden{
display: none;
}
</style>
<script lang="ts">
private testData: any[] ;
/*关键代码: 合并单元格 */
private combineCell(list:any):void {
for (let field in list[0]) {
let k = 0;
while (k < list.length) {
list[k][field + 'span'] = 1;
list[k][field + 'dis'] = false;
for (var i = k + 1; i <= list.length - 1; i++) {
if (list[k][field] == list[i][field] && list[k][field] != '') {
list[k][field + 'span']++;
list[k][field + 'dis'] = false;
list[i][field + 'span'] = 1;
list[i][field + 'dis'] = true;
} else {
break;
}
}
k = i;
}
}
return list;
}
private mounted(): void {
/* 初始化 */
this.combineCell(this.testData);
}
};
</script>
复制代码
如代码所示,遍历数组,当上下两个数,值相同时,给数组中加两个新的参数dis+"" ,(" "+span),同时计算出相同值的个数(" "+span),而通过表格中的rowspan = " "+span给第一个不同的值,而后给其他的相同的绑定class,将其dispaly:none掉。最终实现自动合并的效果。