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?
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?
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);
HSSFCellStyle style=workbook.createCellStyle();
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
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);
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);
Use XSSFCellStyle.BORDER_MEDIUM
or XSSFBorderFormatting.BORDER_MEDIUM
(both enums refer to the same value):
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);
Use setBorderColor(XSSFCellBorder.BorderSide.BOTTOM, XSSFColor)
or setBottomBorderColor(XSSFColor)
(equivalent for top, left, right):
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);
From Version 4.0.0 on RegionUtil
-methods have a new signature. For example:
RegionUtil.setBorderBottom(BorderStyle.DOUBLE,
CellRangeAddress.valueOf("A1:B7"), sheet);
To create a border in Apache POI you should...
1: Create a style
final XSSFCellStyle style = workbook.createCellStyle();
2: Then you have to create the border
style.setBorderBottom( new XSSFColor(new Color(235,235,235));
3: Then you have to set the color of that border
style.setBottomBorderColor( new XSSFColor(new Color(235,235,235));
4: Then apply the style to a cell
cell.setCellStyle(style);