Java – Apache POI rows number

apache-poijava

I am using Apache POI java and want to get the total number of rows which are not empty. I successfully processed a whole row with all its columns. Now I am assuming that I get an excel sheet with multiple rows and not a single row…so how to go about that? I was thinking of getting total number of rows (int n) and then loop until i<=n but not sure.

Suggestions are most welcome 🙂

Note: Apache POI version is 3.8. I am not dealing with Xlsx format…only xls.

Yes I tried this code but got 20 in return….which is not possible given I have only 5 rows

FileInputStream fileInputStream = new FileInputStream("COD.xls");
            HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
            HSSFSheet worksheet = workbook.getSheet("COD");
            HSSFRow row1 = worksheet.getRow(3);
            Iterator rows = worksheet.rowIterator(); 
            int noOfRows = 0;
            while( rows.hasNext() ) {
                HSSFRow row = (HSSFRow) rows.next();
                noOfRows++;                
            }
            System.out.println("Number of Rows: " + noOfRows);

Best Answer

for (int i = 0; i <= sheet.getLastRowNum(); i++) {
    if ((tempRow = sheet.getRow(i)) != null) {
           //Your Code Here
    }
}
Related Topic