[alibaba/easyexcel]Excel填充数据时,如何在所有数据都写入表格之后触发操作?

2024-01-04 701 views
9

EasyExcel 3.2.0 版本,填充; 我想在所有数据都写入模板之后,进行某些操作,比如修改样式、加粗框线等,应该实现哪个接口? 之前是实现WorkbookWriteHandler,重写public void afterWorkbookDispose(WriteWorkbookHolder writeWorkbookHolder)方法,但是效果不行

回答

4

我也有类似场景问题,我在处理合并单元格后,发现合并后的单元格在excel工具中公式计算时发现还是计算了合并前每个单元格的值,想尝试重写afterWorkbookDispose将其他单元格清空,发现获取到sheet的数据只有最后100行数据,总数据应有120行

@Override
public void afterWorkbookDispose(WriteWorkbookHolder writeWorkbookHolder) {
    Iterator<Sheet> sheetIterator = writeWorkbookHolder.getWorkbook().sheetIterator();
    while (sheetIterator.hasNext()) {
        Sheet sheet = sheetIterator.next();
        List<CellRangeAddress> mergedRegions = sheet.getMergedRegions();
        if (CollectionUtils.isEmpty(mergedRegions)) {
            continue;
        }
        for (CellRangeAddress mergedRegion : mergedRegions) {
            for (int ri = mergedRegion.getFirstRow(); ri <= mergedRegion.getLastRow(); ri++) {
                Row row = sheet.getRow(ri);
                for (int ci = mergedRegion.getFirstColumn(); ci <= mergedRegion.getLastColumn(); ci++) {
                    // 保留左上角单元格值
                    if (ri == mergedRegion.getFirstRow() && ci == mergedRegion.getFirstColumn()) {
                        continue;
                    }
                    row.getCell(ci).setCellValue((String) null);
                }
            }
        }
    }
}
9

试试设置 builder.inMemory(true) 估计是因为默认用了 SXSSF API 的 SXSSFWorkbook,有个 DEFAULT_WINDOW_SIZE,默认值是100。

2

@Override public void afterWorkbookDispose(WriteWorkbookHolder writeWorkbookHolder) { Workbook workbook = writeWorkbookHolder.getWorkbook(); Sheet sheet = workbook.getSheetAt(0); CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setBorderBottom(BorderStyle.THICK);

Integer lastRowIndex = rowIndexList.get(rowIndexList.size() - 1);
Row row = sheet.getRow(lastRowIndex);
for (int i = firstColumnIndex; i < lastColumnIndex; i++) {
    Cell cell = row.getCell(i);
    cell.setCellStyle(cellStyle);
}

} 发现获取的Row是空的 ,null