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 ?
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.
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.
$objPHPExcel->setActiveSheetIndex(0)->getHighestDataRow(); Use the getHighestDataRow() method to get the highest row number for cells that have actual content.
Try Sheet.getPhysicalNumberOfRows()
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With