Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 837
Ahmad Avatar asked Apr 26 '13 10:04

Ahmad


People also ask

How do I count data in a row in Excel?

If you need a quick way to count rows that contain data, select all the cells in the first column of that data (it may not be column A). Just click the column header. The status bar, in the lower-right corner of your Excel window, will tell you the row count.

Does Apache POI help to read Excel file?

To Read and Write Excel file in Java, Apache provides a very famous library POI. This library is capable enough to read and write both XLS and XLSX file format of Excel. To read XLS files, an HSSF implementation is provided by POI library.

How do I count the number of rows in Excel using PHP?

$objPHPExcel->setActiveSheetIndex(0)->getHighestDataRow(); Use the getHighestDataRow() method to get the highest row number for cells that have actual content.


2 Answers

Try Sheet.getPhysicalNumberOfRows()

like image 175
macias Avatar answered Sep 20 '22 08:09

macias


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.

like image 29
MatthijsM Avatar answered Sep 22 '22 08:09

MatthijsM