Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the last row in an Excel spreadsheet

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.

like image 766
FromCanada Avatar asked Apr 15 '10 13:04

FromCanada


People also ask

How do I find the last row?

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.

How do I find the last non blank row in Excel?

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.

How do you go to the last row in sheets?

Using the keyboard shortcut Ctrl+↓, we can jump to the cell just above the first blank cell in a column.

What is the last row number in Excel?

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.


1 Answers

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

like image 62
trashgod Avatar answered Sep 19 '22 18:09

trashgod