1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| static class CustomMergeCellHandler extends AbstractMergeStrategy {
private List<String> mergeFields; private int count; public CustomMergeCellHandler(List<String> mergeFields,int count){ this.mergeFields = mergeFields; this.count = count; }
private Map<String, Pair<Object,Integer>> previousValueMap = new HashMap<>();
@Override protected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {
int curRowNum = relativeRowIndex+1; if(mergeFields != null && mergeFields.size() > 0){ if(mergeFields.contains(head.getFieldName())){ if(previousValueMap.containsKey(head.getFieldName())){ Pair<Object, Integer> pair = previousValueMap.get(head.getFieldName()); Object curValue = getCellValue(cell);
if(!pair.getLeft().equals(curValue)){ if(curRowNum - pair.getRight() > 1){ sheet.addMergedRegion(new CellRangeAddress(pair.getRight(), curRowNum - 1, cell.getColumnIndex(), cell.getColumnIndex())); } previousValueMap.put(head.getFieldName(),Pair.of(curValue,curRowNum)); } else { if(count == curRowNum){ if(curRowNum - pair.getRight() > 1){ sheet.addMergedRegion(new CellRangeAddress(pair.getRight(), curRowNum, cell.getColumnIndex(), cell.getColumnIndex()));
previousValueMap.put(head.getFieldName(),Pair.of(curValue,curRowNum)); } }
}
} else { Object curValue = getCellValue(cell); previousValueMap.put(head.getFieldName(),Pair.of(curValue,curRowNum)); } } } }
protected Object getCellValue(Cell cell) { if (Objects.isNull(cell)) { return ""; }
CellType cellTypeEnum = cell.getCellTypeEnum(); switch (cellTypeEnum) { case STRING: return cell.getStringCellValue(); case BOOLEAN: return cell.getBooleanCellValue(); case NUMERIC: return cell.getNumericCellValue(); default: return ""; } } }
|