[java] How to get row count in an Excel file using POI library?

Guys I'm currently using the POI 3.9 library to work with excel files. I know of the getLastRowNum() function, which returns a number of rows in an Excel file.

The only problem is getLastRowNum() returns a number with the count starting from 0.

So if an Excel file uses the first 3 rows, getLastRowNum() returns 2. If an Excel file has just 1 row, getLastRowNum() returns 0.

The problem occurs when the Excel file is completely empty. getLastRowNum() still returns 0, so I cannot determine if the Excel file has 1 row of data, or if its empty.

So how can I detect if an Excel file is empty or not ?

This question is related to java excel apache-poi poi-hssf

The answer is


There are two Things you can do

use

int noOfColumns = sh.getRow(0).getPhysicalNumberOfCells();

or

int noOfColumns = sh.getRow(0).getLastCellNum();

There is a fine difference between them

  1. Option 1 gives the no of columns which are actually filled with contents(If the 2nd column of 10 columns is not filled you will get 9)

  2. Option 2 just gives you the index of last column. Hence done 'getLastCellNum()'


Since Sheet.getPhysicalNumberOfRows() does not count empty rows and Sheet.getLastRowNum() returns 0 both if there is one row or no rows, I use a combination of the two methods to accurately calculate the total number of rows.

int rowTotal = sheet.getLastRowNum();

if ((rowTotal > 0) || (sheet.getPhysicalNumberOfRows() > 0)) {
    rowTotal++;
}

Note: This will treat a spreadsheet with one empty row as having none but for most purposes this is probably okay.


If you do a check

if
(getLastRowNum()<1){
 res="Sheet Cannot be empty";
return
}

This will make sure you have at least one row with data except header. Below is my program which works fine. Excel file has three columns ie. ID, NAME , LASTNAME

XSSFWorkbook workbook = new XSSFWorkbook(inputstream);
        XSSFSheet sheet = workbook.getSheetAt(0);
        Row header = sheet.getRow(0);
        int n = header.getLastCellNum();
        String header1 = header.getCell(0).getStringCellValue();
        String header2 = header.getCell(1).getStringCellValue();
        String header3 = header.getCell(2).getStringCellValue();
        if (header1.equals("ID") && header2.equals("NAME")
                && header3.equals("LASTNAME")) {
            if(sheet.getLastRowNum()<1){
                System.out.println("Sheet empty");
                         return;
            }   
                        iterate over sheet to get cell values
        }else{
                          SOP("invalid format");
                          return;
                          }

To find last data row, in case you created table template in excel where it is filled partially or in between rows are empty. Logic:

int count = 0;
int emptyrow=0;
int irow=0;
while (rowIterator.hasNext()) {
    row = (Row) rowIterator.next();
    if (count != 0 && !checkIfRowIsEmpty(row)) { }
    else{
        if(count!=0 && emptyrow==irow){
            emptyrow++;
        }else{
            emptyrow=0;
            irow=0;
        }
    }
    if(emptyrow>0){
        irow++;
    }
    if(emptyrow>3){
        break;
    }
    count++;
}

Sheet.getPhysicalNumberOfRows() does not involve some empty rows. If you want to loop for all rows, do not use this to know the loop size.


getLastRowNum() return index of last row.

So if you wants to know total number of row = getLastRowNum() +1.

I hope this will work.

int rowTotal = sheet.getLastRowNum() +1;

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to excel

Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support Converting unix time into date-time via excel How to increment a letter N times per iteration and store in an array? 'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data) How to import an Excel file into SQL Server? Copy filtered data to another sheet using VBA Better way to find last used row Could pandas use column as index? Check if a value is in an array or not with Excel VBA How to sort dates from Oldest to Newest in Excel?

Examples related to apache-poi

Alternative to deprecated getCellType Apache POI error loading XSSFWorkbook class Cannot get a text value from a numeric cell “Poi” org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Merging cells in Excel using Apache POI get number of columns of a particular row in given excel using Java How to get row count in an Excel file using POI library? How to check if an excel cell is empty using Apache POI? What is the better API to Reading Excel sheets in java - JXL or Apache POI Using Apache POI how to read a specific excel column

Examples related to poi-hssf

How to get row count in an Excel file using POI library? How to insert a row between two rows in an existing excel with HSSF (Apache POI)