How to find number of rows from Excel using Apache POI API?
In this tutorial we are going to understand how to find total number of Rows in the excel sheet.
Program to find number of rows from Excel using Apache POI api
Step 1 : Importing of necessary packages
// package from Fileinput
import java.io.FileInputStream;
// packages from apache POI
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
Step 2 : To read the data from Excel, we are using FileInputStream
Path refers to location of the excelsheet.
FileInputStream ExcelFile = new FileInputStream(path);
Step 3 : Open the existing workbook instance of xlxs file
XSSFWorkbook ExcelWBook = new XSSFWorkbook(ExcelFile);
Step 4 : Access the existing worksheet of xlsx file, in this instance it is “Sheet1”
XSSFSheet ExcelWSheet = ExcelWBook.getSheet(“Sheet1”);
Step 5 : Will return the total number of rows in the excel sheet.
Return type is integer.
int totalRows = ExcelWSheet.getPhysicalNumberOfRows();
Step 6 : Will print the total number of rows in the excel sheet
System.out.println(“Total number of Rows :::”+totalRows);
Program :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package excel; //list of packages imported import java.io.FileInputStream; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelRows { public static void main(String args[]) throws Exception { String path = “C:\sampleData.xlsx”; // Open the Excel file FileInputStream ExcelFile = new FileInputStream(path); // Access the required test data sheet XSSFWorkbook ExcelWBook = new XSSFWorkbook(ExcelFile); XSSFSheet ExcelWSheet = ExcelWBook.getSheet(“Sheet1”); int totalRows = ExcelWSheet.getPhysicalNumberOfRows(); System.out.println(“Total number of Rows :::”+totalRows); } } |