将样式应用于单元格范围 - Apache POI

nak*_*ada 5 java apache excel styles apache-poi

我正在寻找一种解决方案,将样式应用到一系列单元格,而不必对其进行循环。

尝试了在 stackoverflow 上找到的其他解决方案,但没有一个有效。例如,这对我不起作用:

CellRangeAddress region = CellRangeAddress.valueOf("A1:B2");
short borderStyle = CellStyle.BORDER_THIN;
RegionUtil.setBorderBottom(borderStyle, region, activeSheet, excelWorkbook);
RegionUtil.setBorderTop(borderStyle, region, activeSheet, excelWorkbook);
RegionUtil.setBorderLeft(borderStyle, region, activeSheet, excelWorkbook);
RegionUtil.setBorderRight(borderStyle, region, activeSheet, excelWorkbook);
Run Code Online (Sandbox Code Playgroud)

它在选区的外边缘添加边框,而不是在内部的单元格上添加边框。我想为范围内的每个单元格设置一个边框。没有循环就可以吗?

谢谢

小智 4

我认为您不能将样式应用于范围单元格内的所有单元格,而不将其单独应用于单个单元格。

尝试循环遍历每个单元格并应用所有边框。

这是一个可能对您有帮助的示例:

CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setBorderLeft(CellStyle.BORDER_THIN);
cellStyle.setBorderRight(CellStyle.BORDER_THIN);
cellStyle.setBorderTop(CellStyle.BORDER_THIN);
cellStyle.setBorderBottom(CellStyle.BORDER_THIN);
for(int i=region.getFirstRow();i<region.getLastRow();i++){
    Row row = sheet.getRow(i);
    for(int j=region.getFirstColumn();j<region.getLastColumn();j++){
        Cell cell = row.getCell(j);
        cell.setCellStyle(cellStyle);
    }
}
Run Code Online (Sandbox Code Playgroud)