今天过客遇到一个需要合并单元格的业务,但是之前过客用的一直是easyExcel框架,所以这次也不想去使用其他的框架,今天就跟大家讲讲easyExcel怎么进行单元格的合并。
首先使用easyExcel进行导出的实体类一样是依据之前那样写,之后在编写导出代码时候使用
.registerWriteHandler(new CustomMergeStrategy()) 方法,其中CustomMergeStrategy为自定义策略类。
EasyExcel.write(outputStream)
.head(CombinationGoodsExcel.class)
.registerWriteHandler(new CustomMergeStrategy())
下面附上CustomMergeStrategy类代码:
package com.cfood.mdm.converter;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.util.List;
public class CustomMergeStrategy implements CellWriteHandler {
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
if (isHead){
//如果是表头不做处理
return;
}
//如果当前是第一行不做处理
if(relativeRowIndex==0){
return;
}
//获取当前行下标,上一行下标,上一行对象,上一列对象
Sheet sheet = cell.getSheet();
int rowIndex = cell.getRowIndex();
int rowIndexPrev=rowIndex- 1;
Row row = sheet.getRow(rowIndexPrev);
Cell cellPrev = row.getCell(cell.getColumnIndex());
//得到当前单元格值和上一行单元格
Object cellValue =cell.getCellType()== CellType.STRING?cell.getStringCellValue() : cell.getNumericCellValue();
Object cellValuePrev =cellPrev.getCellType()==CellType.STRING?cellPrev.getStringCellValue():cellPrev.getNumericCellValue();
System.out.println("cellValuePrev = " + cellValuePrev);
System.out.println("cellValue = " + cellValue);
//如果当前单元格和上一行单元格值相等就合并
if (!cellValue.equals(cellValuePrev)) {
return;
}
//获取已有策略
List<CellRangeAddress> mergedRegions = sheet.getMergedRegions();
boolean mergen=false;
for (int i = 0; i < mergedRegions.size(); i++) {
CellRangeAddress cellAddresses = mergedRegions.get(i);
if(cellAddresses.isInRange(rowIndexPrev,cell.getColumnIndex())){
sheet.removeMergedRegion(i);
cellAddresses.setLastRow(rowIndex);
sheet.addMergedRegion(cellAddresses);
mergen=true;
break;
}
}
if (!mergen){
CellRangeAddress cellAddresses = new CellRangeAddress(rowIndexPrev, rowIndex, cell.getColumnIndex(), cell.getColumnIndex());
sheet.addMergedRegion(cellAddresses);
}
}
}
像这样就可以完成单元格的合并了。如图功效: