This commit is contained in:
haomingming 2026-01-04 14:15:19 +08:00
parent 3a7c6aa4e3
commit e4b4423b66

View File

@ -18,6 +18,7 @@ public class CustomExcelWriteHandler implements WriteHandler {
private final double totalTotal;
private final int dataSize;
private boolean totalRowCreated = false;
private int processedDataRowCount = 0; // 已处理的数据行数
// 缓存 Workbook afterSheetCreate 中初始化
private Workbook workbook;
@ -64,12 +65,24 @@ public class CustomExcelWriteHandler implements WriteHandler {
headRow.setHeightInPoints(25);
}
// 关键数据行写入完成后创建合计行兼容低版本
// 设置数据行行高并在最后一行数据写入后创建合计行
public void afterRowDispose(WriteSheetHolder writeSheetHolder, Row row, Integer relativeRowIndex, Boolean isHead) throws IOException {
// 仅在最后一行数据写入后创建合计行且未创建过
if (!totalRowCreated && relativeRowIndex != null && relativeRowIndex == dataSize - 1) {
Sheet sheet = writeSheetHolder.getSheet();
// 设置数据行行高排除表头行
if (isHead == null || !isHead) {
processedDataRowCount++;
if (row.getRowNum() >= 2 && row.getRowNum() <= 1 + dataSize) {
row.setHeightInPoints(22);
}
// 如果是最后一行数据创建合计行
if (!totalRowCreated && processedDataRowCount == dataSize && dataSize > 0) {
createTotalRow(writeSheetHolder.getSheet());
}
}
}
// 创建合计行的辅助方法
private void createTotalRow(Sheet sheet) throws IOException {
// 修正合计行索引0=大标题1=表头2~1+dataSize=数据2+dataSize=合计
int totalRowIndex = 2 + dataSize;
Row totalRow = sheet.createRow(totalRowIndex);
@ -90,7 +103,7 @@ public class CustomExcelWriteHandler implements WriteHandler {
totalStyle.setBorderLeft(BorderStyle.THIN);
totalStyle.setBorderRight(BorderStyle.THIN);
// 合并前6列写合计
// 合并前6列写"合计"
sheet.addMergedRegion(new CellRangeAddress(totalRowIndex, totalRowIndex, 0, 5));
Cell totalCell = totalRow.createCell(0);
totalCell.setCellValue("合计");
@ -137,9 +150,11 @@ public class CustomExcelWriteHandler implements WriteHandler {
}
}
// 设置数据行行高
if (row.getRowNum() >= 2 && row.getRowNum() <= 1 + dataSize) {
row.setHeightInPoints(22);
// 备用在所有数据写入完成后创建合计行如果 afterRowDispose 中没有创建
public void afterSheetDispose(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) throws IOException {
// 如果合计行还未创建则创建备用方案
if (!totalRowCreated && dataSize > 0) {
createTotalRow(writeSheetHolder.getSheet());
}
}