简体   繁体   中英

NullPointerException when reading from xlsx file

I am reading data from an Excel file, which I put later in a MySQL database in the same Java program. I had a problem adding data to the database: Eclipse kept showing a NullPointerException error. I worked with getLastRowNum(), which also counted some empty cells after the filled cells. This problem was fixed with this code (here I only count the amount of filled cells and work with this instead of the last row number):

int rows = Sname.getLastRowNum();
int rows2 = 0;

for(int kk = 1; kk<= rows; kk++)
{
  XSSFRow row = Sname.getRow(kk);
  XSSFCell cell = row.getCell(0);

  if(cell != null)
  {
  rows2++;
  }
}

Last week it worked, but now I get a java.lang.NullPointerException at XSSFCell cell = row.getCell(0);

And I don't understand why. Can somebody help me? Thank you!

我认为您的for应该从0开始而不是从1开始,然后转到rows-1

Either Sname.getLastRowNum(); or Sname.getRow(kk) are throwing NPE. Make sure you have initialized Sname

Also Look at your for loop:

for(int kk = 1; kk<= rows; k++)

Does this even compile? If yes, please replace 'k++' with 'kk++' or else you would end up having infinite iterations.

I think the problem is in the limit of the loop. It should go to kk < rows instead of kk <= rows .

In fact, before testing this solution, I would try to log the value for Sname.getLastRowNum() and watch what value it has.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM