I'm trying to find the index of the last row in an excel spreadsheet using Apache's POI for Java.
I thought this should be possible with getLastRowNum()
or getPhysicalNumberOfRows()
but they don't seem to give the right results. For example, I have a one line spreadsheet and these two functions return a value of 1140. Another two line spreadsheets gets a value of 1162.
The other problem is that I cannot just look for the first empty row, since it may be possible to have empty rows between rows of valid data.
So is there a way to find the index of the last row? I suppose I could make it a requirement to not have empty rows between data, but I was hoping for a better solution.
Edit: For the record using an iterator didn't help. It just iterated over the 1140/1162 supposed rows.
We will use the shortcut key Ctrl + down arrow. It will take us to the last used row before any empty cell. We will also use the same VBA method to find the last row.
Return the row number of the last non blank cell: Enter the formula: =SUMPRODUCT(MAX((A2:A20<>"")*ROW(A2:A20))) into a blank cell to locate the calculated result, and then press Enter key to return the correct result, see screenshot: Note: In the above formulas, A2:A20 is the range of cells that you want to use.
Using the keyboard shortcut Ctrl+↓, we can jump to the cell just above the first blank cell in a column.
However, when entered in a single cell, the ROW function returns only the first row in our range, which is 4. The ROWS function also returns 4, because there are four rows in our range. The formula becomes 4 + 4 – 1 = 7. Therefore, the final result in cell E4 is 7, which is the last row number in our range.
I get the expected output using poi-3.6-20091214 and a test.xls
having two empty rows followed by three occupied rows:
InputStream myxls = new FileInputStream("test.xls");
Workbook book = new HSSFWorkbook(myxls);
Sheet sheet = book.getSheetAt(0);
System.out.println(sheet.getLastRowNum());
Output: 4
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