Add border to merged cells in excel Apache poi java.?

ashu picture ashu · Dec 18, 2012 · Viewed 42.7k times · Source

I'm using Apache POI and I need to put a border in a range of cells or merged region. I am merging the cells with three rows and five columns. But I am not able to add the border to it. So how do I do this?

Answer

pedromendessk picture pedromendessk · Dec 23, 2013

My solution was to merge the cells by their positions, then created a cell (reference to the first block of the merged cells) to assign a value and then set the border throught the HSSFRegionUtil

// Merges the cells
CellRangeAddress cellRangeAddress = new CellRangeAddress(start, start, j, j + 1);
sheet.addMergedRegion(cellRangeAddress);

// Creates the cell
Cell cell = CellUtil.createCell(row, j, entry.getKey());

// Sets the borders to the merged cell
HSSFRegionUtil.setBorderTop(CellStyle.BORDER_MEDIUM, cellRangeAddress, sheet, workbook);
HSSFRegionUtil.setBorderLeft(CellStyle.BORDER_MEDIUM, cellRangeAddress, sheet, workbook);
HSSFRegionUtil.setBorderRight(CellStyle.BORDER_MEDIUM, cellRangeAddress, sheet, workbook);
HSSFRegionUtil.setBorderBottom(CellStyle.BORDER_THIN, cellRangeAddress, sheet, workbook);