daochu
This commit is contained in:
parent
3a7c6aa4e3
commit
e4b4423b66
@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user