Add borders to cells in POI generated Excel File

I am using POI to generate an Excel File. I need to add borders to specific cells in the worksheet.

How can I accomplish this?


Solution 1:

Setting up borders in the style used in the cells will accomplish this. Example:

style.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);

Solution 2:

In the newer apache poi versions:

XSSFCellStyle style = workbook.createCellStyle();
style.setBorderTop(BorderStyle.MEDIUM);
style.setBorderBottom(BorderStyle.MEDIUM);
style.setBorderLeft(BorderStyle.MEDIUM);
style.setBorderRight(BorderStyle.MEDIUM);

Solution 3:

HSSFCellStyle style=workbook.createCellStyle();
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

Solution 4:

a Helper function:

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);
    }

When you want to add Border in Excel, then

String cellAddr="$A$11:$A$17";

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

Solution 5:

XSSF

BorderStyle

Use XSSFCellStyle.BORDER_MEDIUM or XSSFBorderFormatting.BORDER_MEDIUM (both enums refer to the same value):

final 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);

BorderColor

Use setBorderColor(XSSFCellBorder.BorderSide.BOTTOM, XSSFColor) or setBottomBorderColor(XSSFColor) (equivalent for top, left, right):

final XSSFCellStyle cellStyle = workbook.createCellStyle();
final 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);