Search code examples
javaapache-poixssf

Is it possible to set the active range with Apache POI XSSF?


I am using Apache POI XSSF to read and write Excel Sheets.

I know that I can set the active cell on a worksheet by using Sheet.setActiveCell(CellAddress address).

However, I'd like to set it to a Range containing more than one cell on the sheet, as illustrated by the picture below:

Range selected in Excel Sheet

When I save a sheet with multiple cells selected using Excel those are selected upon opening the saved file. Is there a way to do this with POI XSSF?


Solution

  • you can use following line to achieve a ranke as active cell in excel:

        sheet.setActiveCell("A1:B2");
    

    Hope it helps.

    As from 3.16 onwards the setActiveCell(String) method is deprecated and you do not want to use a deprecated method I would suggest to create your own CellAddress:

    public class CellRangeAddress extends CellAddress {
    
        private CellAddress start;
        private CellAddress end;
    
        public CellRangeAddress(final CellAddress start, final CellAddress end) {
            super(start);
            this.start = start;
            this.end = end;
        }
    
    
        @Override
        public String formatAsString() {
            if (end != null) {
                return start.formatAsString() + ":" + end.formatAsString();
            }
            return super.formatAsString();
        }
    }
    

    and use ist like:

    sheet.setActiveCell(new CellRangeAddress(new CellAddress("A1"), new CellAddress("B2")));
    

    Not the cleanest and best way, but works without warnings.