How to unmerge cells in a spreadsheet using apache

2019-07-08 21:09发布

问题:

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 ?

回答1:

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



回答2:

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);
        }


回答3:

For some reason the following code did not remove all the merged regions at once:

logger.info("Number of merged regions = " + sheet.getNumMergedRegions());
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
    logger.info("Removing merged region " + (i + 1));
    sheet.removeMergedRegion(i);
}
logger.info("\nNumber of merged regions = " + sheet.getNumMergedRegions());

In the console I see this:

Number of merged regions = 7
Removing merged region 1
Removing merged region 2
Removing merged region 3
Removing merged region 4

Number of merged regions = 3

Fix:

while (sheet.getNumMergedRegions() > 0) {
    logger.info("Number of merged regions = " + sheet.getNumMergedRegions());
    for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
        logger.info("Removing merged region " + (i + 1));
        sheet.removeMergedRegion(i);
    }
}