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

拟墨画扇 提交于 2020-01-04 03:51:10

问题


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


来源:https://stackoverflow.com/questions/32045517/how-to-unmerge-cells-in-a-spreadsheet-using-apache-poi-java-library

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!