Delete sheet from WorkBook in POI

12,846

You should delete in reverse order, not forward order. Otherwise, you remove a sheet from the list and change the state of it for future loops.

Thing about the case of sheets A, B, C and D. You iterate to i=1, and get B. You delete B. If you don't re-fetch the row at 1, and move on to i=2, you'll be on D and will have skipped C! Iterating through in reverse avoids this problem.

Share:
12,846

Related videos on Youtube

Momo
Author by

Momo

Updated on September 16, 2022

Comments

  • Momo
    Momo over 1 year

    I have a WorkBook and I'm trying to delete sheets which names don't match with a specific String.

    Here is my code

    XSSFWorkbook book = new XSSFWorkbook(new FileInputStream(excelName));                   
                for(int i=0;i<book.getNumberOfSheets();i++){
                    System.out.println(book.getSheetAt(i).getSheetName());
                    if(!book.getSheetAt(i).getSheetName().equals(sheetName)){
                        book.removeSheetAt(i);
                    }
                }   
    

    The code runs well, but it doesn't perform the desired task

    EDIT

    The solution as said is to reverse the loop order. Here is a cleaner code

    private void removeOtherSheets(String sheetName, XSSFWorkbook book) {       
                for(int i=book.getNumberOfSheets()-1;i>=0;i--){
                    XSSFSheet tmpSheet =book.getSheetAt(i);
                    if(!tmpSheet.getSheetName().equals(sheetName)){
                        book.removeSheetAt(i);
                    }
                }       
        }