在Java中使用easyexcel設置邊框線,可以通過StyleStrategy
和WriteCellStyle
來實現。
首先,創建一個自定義的StyleStrategy
,實現org.apache.poi.ss.usermodel.StyleStrategy
接口:
public class CustomStyleStrategy implements StyleStrategy {
@Override
public void registerStyles(Workbook workbook) {
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setBorderTop(BorderStyle.THIN);
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
CellStyle headerStyle = workbook.createCellStyle();
headerStyle.cloneStyleFrom(cellStyle);
headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 注冊樣式
CellStyleUtil.putCellStyle(workbook, cellStyle, true);
CellStyleUtil.putCellStyle(workbook, headerStyle, true);
}
}
然后在寫入Excel時,使用WriteCellStyle
將邊框樣式應用到指定的單元格:
// 創建WriteCellStyle對象,并設置邊框樣式
WriteCellStyle cellStyle = new WriteCellStyle();
cellStyle.setBorderTop(BorderStyle.THIN);
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
// 設置邊框樣式
EasyExcel.write(fileName, Data.class)
.registerWriteHandler(new HorizontalCellStyleStrategy(new CustomStyleStrategy()))
.write(data, EasyExcel.writerSheet(sheetName).build());
通過以上步驟,就可以在Java中使用easyexcel設置邊框線了。