0

Im automating a database using apache poi. I need to get the sum of cell range B3:H3

I have successfully get the output. Now I need to loop the equation for 300+ rows. I used following equation for a single row.

sheet1.getRow(1).createCell(8).setCellValue("TOTAL");
sheet1.getRow(2).createCell(8).setCellFormula("SUM(B3:H3)");

I need to find the last row number and loop the process till then. How can I do that?

Derrick
  • 3,669
  • 5
  • 35
  • 50
LSH94
  • 109
  • 1
  • 9
  • Possible duplicate of [Apache POI rows number](https://stackoverflow.com/questions/9963912/apache-poi-rows-number) – AxelH Jul 17 '18 at 11:53
  • The duplicate doesn't seems to be the same but this what you should have find in a search engine and this holds some interesting way to iterate rows in POI. – AxelH Jul 17 '18 at 11:54

2 Answers2

1
int lastRow = sheet1.getLastRowNum()

You can get the number of the last row contained in a sheet by using getLastRowNum() method.

Also please have a look at HSSFSheet.getPhysicalNumberOfRows

AxelH
  • 14,325
  • 2
  • 25
  • 55
Madhan Varadhodiyil
  • 2,086
  • 1
  • 14
  • 20
  • Is there any way to loop the process until that last row number? This is my very first java project so I don't have a proper idea about looping and I don't have enough time to study the basics. – LSH94 Jul 18 '18 at 03:07
  • You can iterate over rows and columns using for/forEach for (Row row : sheet1) { ///iterate rows for (Cell cell : row) { // iterate columns in each row // do something } } – Madhan Varadhodiyil Jul 18 '18 at 07:13
0

There is a method available on HSSFSheet class

public int getLastRowNum()

HSSFSheet.getLastRowNum

AxelH
  • 14,325
  • 2
  • 25
  • 55
Ultcyber
  • 396
  • 1
  • 6
  • Is there any way to loop the process until that last row number? This is my very first java project so I don't have a proper idea about looping and I don't have enough time to study the basics. – LSH94 Jul 18 '18 at 03:07
  • Just use a standard for loop and use the `int` that got returned from `getLastRowNum()` as the terminating condition `for (int i = 0; i < sheet.getLastRowNum(); ++i)` – Ultcyber Jul 18 '18 at 08:02