Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging cells in Excel using Apache POI

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); 
like image 973
androidDev Avatar asked Sep 10 '13 10:09

androidDev


People also ask

How do I merge cells in Excel using Apache POI?

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.

How do I merge two columns in Excel in 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.

How do I wrap text in Excel using Apache POI?

setWrapText(true); cell. setCellStyle(cellStyle); Saving a file generated with the above code and viewing it in Microsoft Excel will show multiline text in a cell.


2 Answers

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

like image 151
Sankumarsingh Avatar answered Oct 03 '22 06:10

Sankumarsingh


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)); 
like image 25
Suchita Mukherjee Avatar answered Oct 03 '22 07:10

Suchita Mukherjee