Adding border to a merged region in POI XSSF workbook

Charlessmori picture Charlessmori · Jun 30, 2012 · Viewed 31.8k times · Source

I'm using apache poi 3.7 and I need to put border to a range of cells or merged region.

how can I to apply border to a merged region when the sheet and workbook type is XSSF. In HSSF type I use RegionUtil-/HSSFRegionutil, but if use the first object (Regionutil) in XSSF type its doesn't works and puts a black background color to the range of cells.

Regionutil ussually works with CellRangeAddress and i don't find information about this trouble. I don't know if the CellRangeAddres causes this.

Answer

Wee Shetland picture Wee Shetland · Oct 3, 2012

In order to do this, you have to add a blank cell to every cell in the merged region, then add the appropriate borders to each cell. For example, the following code will create a merged region of 5 cells in the same row, with a border around the whole merged region, and the text centred in the region.

XSSFWorkbook wb = new XSSFWorkbook();
CellStyle borderStyle = wb.createCellStyle();
borderStyle.setBorderBottom(CellStyle.BORDER_THIN);
borderStyle.setBorderLeft(CellStyle.BORDER_THIN);
borderStyle.setBorderRight(CellStyle.BORDER_THIN);
borderStyle.setBorderTop(CellStyle.BORDER_THIN);
borderStyle.setAlignment(CellStyle.ALIGN_CENTER);
Sheet sheet = wb.createSheet("Test Sheet");
Row row = sheet.createRow(1);
for (int i = 1; i <= 5; ++i) {
    Cell cell = row.createCell(i);
    cell.setCellStyle(borderStyle);
    if (i == 1) {
        cell.setCellValue("Centred Text");
    } 
}
sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 5));