Site icon TestingDocs.com

Getting number of Rows count from an Excel sheet

Overview

In this post, we will write a simple program to get the number of rows count from an excel sheet. This post is part of excel automation using Apache POI API.

I will use the below excel file in .xlsx format which has 4 rows.

 

Sample program below to get Row count of an Excel sheet:

public class ExcelRowCountExample {
    
    public FileInputStream fis = null;
    public FileOutputStream fileOut = null;

    File file = null ;
    XSSFWorkbook workbook = null ;
    XSSFSheet sheet = null;
    String filename= null;
    
    
public ExcelRowCountExample(String filename) throws IOException {
    this.filename = filename;
    try {
        fis = new FileInputStream(filename);
        workbook = new XSSFWorkbook(fis);
        sheet = workbook.getSheetAt(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally{
            fis.close();
            }
    }
    
    public int getRowCount(String sheetName) {
        int index = workbook.getSheetIndex(sheetName);
        if (index == -1)
            return 0;
        else {
            sheet = workbook.getSheet(sheetName);
            int rowCount = sheet.getLastRowNum() + 1;
            return rowCount;
        }
    }
    
    public static void main(String... args) throws IOException
    {
        ExcelRowCountExample erce = new ExcelRowCountExample("TDocs.xlsx");
        int excelRowCount = erce.getRowCount("MovieList");
        System.out.println("No of rows in the excel sheet:" + excelRowCount );
            
    }
}

 

 

Output of the program:

No of rows in the excel sheet:4

We can see that the program output matches the row count of the above program. Note that, the row index starts from 0. So, to get the correct row count we need to add 1.

One direct implementation of this program is that, we can use this to logic to detect empty excel sheets with no rows in the automation before proceeding further.

Apache POI Tutorials:

https://www.testingdocs.com/apache-poi-tutorials/

More Information on Apache POI API:

https://poi.apache.org/

 

Exit mobile version