在POI生成的Excel文件中为单元格添加边框

jzd*_*jzd 38 java excel border apache-poi

我正在使用POI生成Excel文件.我需要在工作表中的特定单元格中添加边框.

我怎么能做到这一点?

jzd*_*jzd 56

以单元格中使用的样式设置边框将实现此目的.例:

style.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
Run Code Online (Sandbox Code Playgroud)


小智 23

HSSFCellStyle style=workbook.createCellStyle();
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
Run Code Online (Sandbox Code Playgroud)


Mat*_* G. 16

在较新的apache poi版本中:

XSSFCellStyle style = workbook.createCellStyle();
style.setBorderTop(BorderStyle.MEDIUM);
style.setBorderBottom(BorderStyle.MEDIUM);
style.setBorderLeft(BorderStyle.MEDIUM);
style.setBorderRight(BorderStyle.MEDIUM);
Run Code Online (Sandbox Code Playgroud)


小智 11

辅助函数:

private void setRegionBorderWithMedium(CellRangeAddress region, Sheet sheet) {
        Workbook wb = sheet.getWorkbook();
        RegionUtil.setBorderBottom(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderLeft(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderRight(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderTop(CellStyle.BORDER_MEDIUM, region, sheet, wb);
    }
Run Code Online (Sandbox Code Playgroud)

如果要在Excel中添加边框,则

String cellAddr="$A$11:$A$17";
Run Code Online (Sandbox Code Playgroud)

setRegionBorderWithMedium(CellRangeAddress.valueOf(cellAddr1), sheet);


win*_*rrr 8

XSSF

边框

使用XSSFCellStyle.BORDER_MEDIUMXSSFBorderFormatting.BORDER_MEDIUM(两个枚举引用相同的值):

XSSFCellStyle cellStyle = workbook.createCellStyle();

cellStyle.setBorderTop(XSSFCellStyle.BORDER_MEDIUM);
cellStyle.setBorderRight(XSSFCellStyle.BORDER_MEDIUM);
cellStyle.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM);
cellStyle.setBorderLeft(XSSFCellStyle.BORDER_MEDIUM);

cell.setCellStyle(cellStyle);
Run Code Online (Sandbox Code Playgroud)

边框颜色

使用setBorderColor(XSSFCellBorder.BorderSide.BOTTOM, XSSFColor)setBottomBorderColor(XSSFColor)(相当于上,左,右):

XSSFCellStyle cellStyle = workbook.createCellStyle();
XSSFColor color = new XSSFColor(new java.awt.Color(128, 0, 128));

cellStyle.setTopBorderColor(color);
cellStyle.setRightBorderColor(color);
cellStyle.setBottomBorderColor(color);
cellStyle.setLeftBorderColor(color);

cell.setCellStyle(cellStyle);
Run Code Online (Sandbox Code Playgroud)


spe*_*rum 5

如果您使用org.apache.poi.ss.usermodel(不是 HSSF 或 XSSF),您可以使用:

style.setBorderBottom(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
Run Code Online (Sandbox Code Playgroud)

所有的边框样式都可以在 apache 文档中找到