Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 667
ashu Avatar asked Dec 18 '12 10:12

ashu


People also ask

How do you put a border on a merged cell?

Go to Format Cells-->Alignment-->Horizontal and drop the Horizontal box down and select "Center Across Selection". You can then use the range of cells to use BorderAround.

How do I merge cells in Apache POI Java?

sheet = // existing Sheet setup int firstRow = 0; int lastRow = 0; int firstCol = 0; int lastCol = 2 sheet. addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol)); We can also use a cell range reference string to provide the merged region: sheet = // existing Sheet setup sheet.


2 Answers

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);
like image 103
pedromendessk Avatar answered Sep 25 '22 01:09

pedromendessk


You will find the RegionUtil class useful for settings the borders for a range of cells.Look here:

http://poi.apache.org/apidocs/index.html

like image 36
DMV Avatar answered Sep 23 '22 01:09

DMV