导出的excel需要上下行相同的数据进行行合并的功能。如图显示
这里我使用的是项目框架自带的导出模板代码,是在这套模板基础之上做的修改。
// 我主要演示的就是mergeRows方法的操作,dataList是导出数据的集合。
workbook = ExcelTools.expData(workbook, templateSheet);
// 合并行操作
cseQuotaManageCheckService.mergeRows(workbook, dataList);
这是mergeRows方法。
// 合并行操作public void mergeRows(Workbook workbook, List<?> dataList) {if (dataList.isEmpty()) {return;}Sheet sheet = workbook.getSheetAt(0);int startRow = 2; // 数据从第 2 行开始int deptNameCol = 1; // 从第几列开始int benchmarkScoreCol = 2;int finalScoreCol = 3;int daunScoreCol = 4;int i = 0;while (i < dataList.size()) {int mergeStart = i;CseQuotaManageCheckVO current = (CseQuotaManageCheckVO) dataList.get(i);// 查找连续相同的数据行while (i < dataList.size() - 1) {CseQuotaManageCheckVO next = (CseQuotaManageCheckVO) dataList.get(i + 1);if (current.getDeptName().equals(next.getDeptName()) &¤t.getBenchmarkScore().equals(next.getBenchmarkScore()) &¤t.getFinalScore().equals(next.getFinalScore()) &¤t.getDaunScore().equals(next.getDaunScore())) {i++;} else {break;}}// 如果找到多个连续相同的行,则合并它们if (mergeStart != i) {mergeCellsIfNotOverlap(sheet, startRow + mergeStart, startRow + i, deptNameCol, deptNameCol);mergeCellsIfNotOverlap(sheet, startRow + mergeStart, startRow + i, benchmarkScoreCol, benchmarkScoreCol);mergeCellsIfNotOverlap(sheet, startRow + mergeStart, startRow + i, finalScoreCol, finalScoreCol);mergeCellsIfNotOverlap(sheet, startRow + mergeStart, startRow + i, daunScoreCol, daunScoreCol);}// 继续下一个不相同的数据行i++;}}// 解决要合并的区域已经存在合并单元格private void mergeCellsIfNotOverlap(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) {CellRangeAddress newRegion = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);for (int i = 0; i < sheet.getNumMergedRegions(); i++) {CellRangeAddress existingRegion = sheet.getMergedRegion(i);if (isOverlapping(existingRegion, newRegion)) {return; // 跳过合并,因为它与现有合并区域重叠}}sheet.addMergedRegion(newRegion);// 居中操作applyCellStyle(sheet, newRegion);}// 对合并后的行数据内容进行居中显示操作private void applyCellStyle(Sheet sheet, CellRangeAddress region) {Workbook workbook = sheet.getWorkbook();CellStyle centeredStyle = workbook.createCellStyle();centeredStyle.setAlignment(HorizontalAlignment.CENTER);centeredStyle.setVerticalAlignment(VerticalAlignment.CENTER);for (int row = region.getFirstRow(); row <= region.getLastRow(); row++) {for (int col = region.getFirstColumn(); col <= region.getLastColumn(); col++) {Row sheetRow = sheet.getRow(row);if (sheetRow == null) {sheetRow = sheet.createRow(row);}Cell cell = sheetRow.getCell(col);if (cell == null) {cell = sheetRow.createCell(col);}cell.setCellStyle(centeredStyle);}}}private boolean isOverlapping(CellRangeAddress region1, CellRangeAddress region2) {return !(region1.getLastRow() < region2.getFirstRow() ||region1.getFirstRow() > region2.getLastRow() ||region1.getLastColumn() < region2.getFirstColumn() ||region1.getFirstColumn() > region2.getLastColumn());}