Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unmerge cells in a spreadsheet using apache POI java library

We can use sheet.addMergedRegion(rowFrom,rowTo,colFrom,colTo); for adding merged cells in the sheet But I already have a sheet with merged cells in it and I want to unmerge these cells.

Is there any way to unmerge cells of a sheet without creating new sheet using Apache POI ?

like image 601
Nipun Saini Avatar asked Aug 17 '15 08:08

Nipun Saini


2 Answers

Promoting a comment to an answer...

The method you want is Sheet.removeMergedRegion(int)

That takes the index of the region, which you got when you added it. Otherwise, you can use getNumMergedRegions() and getMergedRegion(int) to iterate over the regions to find the index of the one you want to remove

like image 147
Gagravarr Avatar answered Jan 02 '23 11:01

Gagravarr


I just figured out that internally the number of existing regions is checked after every region method. E.g. after removing Region 1 everything is new calculated like size is previousSize-1 and sheet.getNumMergedRegions() is also one less. So for me I added all regions to a list and deleted them from the sheet. I took always id 0 as the id is recalculated everytime.

for(int i = 0; i<numOfRegion;i++)
        {
            regions.add(sheet.getMergedRegion(0));
            sheet.removeMergedRegion(0);
        }
like image 42
Dave Avatar answered Jan 02 '23 11:01

Dave