Search code examples
javaapache-poijxl

How to merge cell using POI in Java


I want to merge cells using POI in java. I have a input sheet which has merged cells.

First I have to get all the merged cells form that sheet. Then I have to create a new with similarly merged cells.

I got merged cells by method getNumMergedRegions().

Which gave me these values: A56:A64=9, A65:A73=9, A2:A8=7, A49:A55=7, A20:A26=7, A9:A19=11, A43:A48=6, A27:A42=16. Now, I want to create a new sheet and want cell merged based on these values. OR can any one help me with any other way using JXL api.


Solution

  • You can use the CellReference to parse the required String, here is a example:

        String[] cellStrings = "A2:A8".split(":");
        CellReference start = new CellReference(cellStrings[0]);
        CellReference end = new CellReference(cellStrings[1]);
    
        CellRangeAddress address = new CellRangeAddress(start.getRow(),
                end.getRow(), start.getCol(), end.getCol());
        System.out.println(address);
    

    This should output:

    org.apache.poi.ss.util.CellRangeAddress [A2:A8]

    Then you can use addMergedRegion from your HSSFSheet instance.