Merging cells in Excel using Apache POI

JavaAndroidExcelApache Poi

Java Problem Overview


Is there any other way to merge cells in Excel using Apache POI library?

I was trying using the following, but its not working

// selecting the region in Worksheet for merging data
CellRangeAddress region = CellRangeAddress.valueOf("A" + rowNo + ":D"
			+ rowNo);

// merging the region
sheet1.addMergedRegion(region);

Java Solutions


Solution 1 - Java

You can use sheet.addMergedRegion(rowFrom,rowTo,colFrom,colTo);

example sheet.addMergedRegion(new CellRangeAddress(1,1,1,4)); will merge from B2 to E2. Remember it is zero based indexing (ex. POI version 3.12).

for detail refer BusyDeveloper's Guide

Solution 2 - Java

You can use :

sheet.addMergedRegion(new CellRangeAddress(startRowIndx, endRowIndx, startColIndx,endColIndx));

Make sure the CellRangeAddress does not coincide with other merged regions as that will throw an exception.

  • If you want to merge cells one above another, keep column indexes same
  • If you want to merge cells which are in a single row, keep the row indexes same
  • Indexes are zero based

For what you were trying to do this should work:

sheet.addMergedRegion(new CellRangeAddress(rowNo, rowNo, 0, 3));

Solution 3 - Java

The best answer

sheet.addMergedRegion(new CellRangeAddress(start-col,end-col,start-cell,end-cell));

Solution 4 - Java

I create a method that merge cells and put border if you want.

protected void setMerge(Sheet sheet, int numRow, int untilRow, int numCol, int untilCol, boolean border) {
	CellRangeAddress cellMerge = new CellRangeAddress(numRow, untilRow, numCol, untilCol);
	sheet.addMergedRegion(cellMerge);
	if (border) {
		setBordersToMergedCells(sheet, cellMerge);
	}

}  

protected void setBordersToMergedCells(Sheet sheet, CellRangeAddress rangeAddress) {
	RegionUtil.setBorderTop(BorderStyle.MEDIUM, rangeAddress, sheet);
	RegionUtil.setBorderLeft(BorderStyle.MEDIUM, rangeAddress, sheet);
	RegionUtil.setBorderRight(BorderStyle.MEDIUM, rangeAddress, sheet);
	RegionUtil.setBorderBottom(BorderStyle.MEDIUM, rangeAddress, sheet);
}

Solution 5 - Java

syntax is:

sheet.addMergedRegion(new CellRangeAddress(start-col,end-col,start-cell,end-cell));

Example:

sheet.addMergedRegion(new CellRangeAddress(4, 4, 0, 5));

Here the cell 0 to cell 5 will be merged of the 4th row.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionandroidDevView Question on Stackoverflow
Solution 1 - JavaSankumarsinghView Answer on Stackoverflow
Solution 2 - JavaSuchita MukherjeeView Answer on Stackoverflow
Solution 3 - JavaVishwanath KalajeView Answer on Stackoverflow
Solution 4 - JavaJesús SánchezView Answer on Stackoverflow
Solution 5 - JavaAishi MitraView Answer on Stackoverflow