在EasyExcel中自定义拦截器不仅可以帮助我们不止步于数据的填充,而且可以对样式、单元格合并等带来便捷的功能。下面直接开始
我们定义一个MergeWriteHandler的类继承AbstractMergeStrategy实现CellWriteHandler
public class MergeLastWriteHandler extends AbstractMergeStrategy implements CellWriteHandler
当中我们重写merge方法
@Override
protected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {
}
我们可以在重写的方法中得到形参中的Cel,那我们可以通过调用cell.getStringCellValue()得到当前单元格的内容,判断当前单元格的内容是否是目标单元格,例如下面代码
if (cell.getStringCellValue().equals("说明")) {
cell.setCellValue("说明:这是一条说明");
//获取表格最后一行
int lastRowNum = sheet.getLastRowNum();
CellRangeAddress region = new CellRangeAddress(lastRowNum, lastRowNum, 0, 5);
sheet.addMergedRegionUnsafe(region);
}
并且这里我们通过sheet中的 getLastRowNum()获取最后一行,最终通过CellRangeAddress来进行单元格合并,从下面源码我们可以了解到合并的规则是什么(通过int firstRow, int lastRow, int firstCol, int lastCol)
/**
* Creates new cell range. Indexes are zero-based.
*
* @param firstRow Index of first row
* @param lastRow Index of last row (inclusive), must be equal to or larger than {@code firstRow}
* @param firstCol Index of first column
* @param lastCol Index of last column (inclusive), must be equal to or larger than {@code firstCol}
*/
public CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol) {
super(firstRow, lastRow, firstCol, lastCol);
if (lastRow < firstRow || lastCol < firstCol) {
throw new IllegalArgumentException("Invalid cell range, having lastRow < firstRow || lastCol < firstCol, " +
"had rows " + lastRow + " >= " + firstRow + " or cells " + lastCol + " >= " + firstCol);
}
}
这样就可以实现合并单元格,不过这里可能会出现一个问题
java.lang.Illega