I am using Apache POI java and want to get the total number of rows which are not empty. I successfully processed a whole row with all its columns. Now I am assuming that I get an excel sheet with multiple rows and not a single row...so how to go about that? I was thinking of getting total number of rows (int n) and then loop until i<=n but not sure.
Suggestions are most welcome :)
Note: Apache POI version is 3.8. I am not dealing with Xlsx format...only xls.
Yes I tried this code but got 20 in return....which is not possible given I have only 5 rows
FileInputStream fileInputStream = new FileInputStream("COD.xls");
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet worksheet = workbook.getSheet("COD");
HSSFRow row1 = worksheet.getRow(3);
Iterator rows = worksheet.rowIterator();
int noOfRows = 0;
while( rows.hasNext() ) {
HSSFRow row = (HSSFRow) rows.next();
noOfRows++;
}
System.out.println("Number of Rows: " + noOfRows);
Find the Count of Rows Now, let's find the index of the last row on a given Sheet. Apache POI provides two methods that help count rows: getLastRowNum() and getPhysicalNumberOfRows().
We can count the total number of rows in a table in Selenium. The rows of a table are represented by <tr> tag in html code. To get all the rows, we shall use the locator xpath and then use find_elements_by_xpath method. The list of rows will be returned.
getLastRowNum() return index of last row. So if you wants to know total number of row = getLastRowNum() +1.
getLastRowNum. Gets the last row on the sheet Note: rows which had content before and were set to empty later might still be counted as rows by Excel and Apache POI, so the result of this method will include such rows and thus the returned value might be higher than expected!
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
if ((tempRow = sheet.getRow(i)) != null) {
//Your Code Here
}
}
The problem is that POI considers empty rows as physical rows. This happens at times in Excel and while they are not visible to the eye, the rows certainly exist.
If you were to open you Excel sheet and select everything below your data, then delete it (i know it is empty looking, but do it anyway), POI will return the right number.
You may want to getPhysicalNumberOfRows() other than getLastRowNum()?
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