将数据一条一条查出来 千万不要用一对多查询 最后用方法进行合并
public class ExcelFileCellMergeStrategy implements CellWriteHandler{
/**
* 合并列的范围索引
*/
private int[] mergeColumnIndex;
/**
* 合并起始行索引
*/
private int mergeRowIndex;
/**
* 合并校验列值
*/
private int colIndex;
public ExcelFileCellMergeStrategy(int[] mergeColumnIndex, int mergeRowIndex, int colIndex) {
this.mergeColumnIndex = mergeColumnIndex;
this.mergeRowIndex = mergeRowIndex;
this.colIndex = colIndex;
}
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
//当前行
int curRowIndex = cell.getRowIndex();
//当前列
int curColIndex = cell.getColumnIndex();
//某行开始合并
if (curRowIndex > mergeRowIndex) {
//判断每行的第一列是否相同,相同时进行合并
if (isSame(cell, curRowIndex)) {
for (int columnIndex : mergeColumnIndex) {
//对应的列进行合并
if (curColIndex == columnIndex) {
mergeWithPrevRow(writeSheetHolder, cell, curRowIndex, curColIndex);
break;
}
}
}
}
}
private Boolean isSame(Cell cell, int curRowIndex){
//获取当前行的某列的数据
Cell curCell = cell.getSheet().getRow(curRowIndex).getCell(colIndex);
//当前行某列值
Object curData = curCell.getCellTypeEnum() == CellType.STRING ? curCell.getStringCellValue() : curCell.getNumericCellValue();
//获取当前行的上一行数据
Cell preCell = cell.getSheet().getRow(curRowIndex - 1).getCell(colIndex);
//上一行某列值
Object preData = preCell.getCellTypeEnum() == CellType.STRING ? preCell.getStringCellValue() : preCell.getNumericCellValue();
// 比较当前行的某列的单元格与上一行是否相同,相同合并当前单元格与上一行
return curData.equals(preData);
}
private void mergeWithPrevRow(WriteSheetHolder writeSheetHolder, Cell cell, int curRowIndex, int curColIndex) {
//获取当前行的当前列的数据和上一行的当前列数据,通过上一行数据是否相同进行合并
Object curData = cell.getCellTypeEnum() == CellType.STRING ? cell.getStringCellValue() : cell.getNumericCellValue();
Cell preCell = cell.getSheet().getRow(curRowIndex - 1 ).getCell(curColIndex);
Object preData = preCell.getCellTypeEnum() == CellType.STRING ? preCell.getStringCellValue() : preCell.getNumericCellValue();
//比较当前行的第一列的单元格与上一行是否相同,相同合并当前单元格与上一行
if (curData.equals(preData)){
Sheet sheet = writeSheetHolder.getSheet();
List<CellRangeAddress> mergedRegions = sheet.getMergedRegions();
boolean isMerged = false;
for (int i = 0; i < mergedRegions.size() && !isMerged; i++) {
CellRangeAddress cellAddresses = mergedRegions.get(i);
//若上 一个单元格已经被合并,则先移出原有的合并单元,再重新添加合并单元
if (cellAddresses.isInRange(curRowIndex - 1 , curColIndex)){
sheet.removeMergedRegion(i);
cellAddresses.setLastRow(curRowIndex);
sheet.addMergedRegion(cellAddresses);
isMerged = true;
}
}
//若上一个单元格未被合并,则新增合并单元
if (!isMerged){
CellRangeAddress cellAddresses = new CellRangeAddress(curRowIndex - 1, curRowIndex, curColIndex, curColIndex);
sheet.addMergedRegion(cellAddresses);
}
}
}
}
这个是进行合并的类方法 到时候导入到类里面直接调用就行
可以直接粘贴复制 不需要修改
标签:int,合并,EasyExcel,导出,cell,curColIndex,一对,preCell,curRowIndex From: https://www.cnblogs.com/yzxsx/p/18325337