How to set border lines in EasyExcel in Java?
In Java, you can set borders using easyexcel by implementing StyleStrategy and WriteCellStyle.
First, create a custom StyleStrategy that implements the org.apache.poi.ss.usermodel.StyleStrategy interface.
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);
}
}
Then, when writing to Excel, use WriteCellStyle to apply the border style to the specified cell:
// 创建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());
By following the above steps, you can set borders in Java using easyexcel.