在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设置边框线了。