0

I'm trying to write a java class that computes the age of the person by getting his/her birth year on excel file. I was successful in computing it and displaying the age on console using System.out.print(age);, however, I'm getting java.lang.NullPointerException on cell.setCellValue(age); Here's a snippet of my code:

int year = Calendar.getInstance().get(Calendar.YEAR);
int age;
for(int i = 0; i < birthdate.size(); i++){
    String bday = birthdate.get(i).toString();
    String y = bday.substring(7, 11);
    age = year - Integer.parseInt(y);
    cell = sheet.getRow(i+1).getCell(5);
    cell.setCellValue(age);
    System.out.print(cell + " \t ");
}

enter image description here

Draken
  • 3,134
  • 13
  • 34
  • 54
ashlrem
  • 117
  • 1
  • 3
  • 17
  • what is the value of cell?Could you please debug? – Ankit Tripathi Oct 04 '16 at 09:13
  • You need to check if the cell exists and if it doesn't exist you need to create it – Erwin Bolwidt Oct 04 '16 at 09:16
  • @Ankit, cell has no value. i will get the year from birthdate cell, and compute the age and pass it on age cell. – ashlrem Oct 04 '16 at 09:25
  • 3
    I hadn't worked with apache poi yet so I may be wrong (which is why I don't want to post it as answer, nor vote to close as duplicate of since canonical question doesn't have solution for this case), but based on `getCell(int)` documentation https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Row.html#getCell(int) it can return null if cell is not defined (I am guessing that it means that when cell doesn't have value). If that is the case then try using overloaded version `getCell(int cellnum, Row.MissingCellPolicy policy)` with `getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);` – Pshemo Oct 04 '16 at 09:25
  • @Pshemo you're awesome! how can I mark your answer? thanks! – ashlrem Oct 04 '16 at 09:29
  • 1
    You can't "accept" comments as answers, and I don't want to post it as such since I am not sure if this is best or even proper approach of handling this problem (since I am not familiar yet with POI library). But feel free to post your own answer which code you are using (if you are sure that it is working as you intended). – Pshemo Oct 04 '16 at 09:35
  • Never mind, I found duplicate, so there is not even need to post another answer. – Pshemo Oct 04 '16 at 09:47

0 Answers0