Apache POI: how to know if a spreadsheet has come to an end?

Asked

Viewed 892 times

0

I am developing a personal project, and for this I am using Java along with Apache POI to read XLS files, how can I know if the spreadsheet has reached its end? Thanks in advance!

1 answer

1


You can use the sheet iterator:

        FileInputStream excelFile = new FileInputStream(new File(FILE_NAME));
        Workbook workbook = new XSSFWorkbook(excelFile);
        Sheet sheet = workbook.getSheetAt(0);
        Iterator<Row> iterator = sheet.iterator();

        while (iterator.hasNext()) {//enquanto houver linhas

            Row currentRow = iterator.next();//obtendo a linha
            Iterator<Cell> cellIterator = currentRow.iterator();//obtendo o iterator da linha (celulas da linha)

            while (cellIterator.hasNext()) {//enquanto houver celulas na linha         

              //fazendo leitura de dados da celula
            }
        }

To get the total number of lines:

int numeroUltimaLinha = sheet.getLastRowNum();//começa em 0, e se a planilha estiver vazia também retorna zero

int numeroTotalLinhas = sheet.getPhysicalNumberOfRows();//nao conta as linhas vazias

If numberLine and numberTotalLines are zero, the spreadsheet is really empty, there are no blank lines and no physical lines.

Example code for reading and writing xls with Apache POI (Mkyoung).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.