1

I'm having a problem with writing in a excel file. I'm using Apache POI to write on the excel.

My code is:

private void EscreverExcel(String Nome) throws FileNotFoundException, IOException{
    File src = new File("D:\\Work\\Fortune\\DadosCliente.xlsx");

    FileInputStream fist = new FileInputStream(src);
    XSSFWorkbook wb = new XSSFWorkbook(fist);
    XSSFSheet sheet = wb.getSheetAt(0);

    sheet.getRow(0).createCell(2).setCellValue(Nome);
    FileOutputStream fos = new FileOutputStream(src);
    wb.write(fos);
    wb.close();
}
public static void main(String[] args) throws IOException{
   Excel ex = new Excel();
   ex.EscreverExcel("Mário");
}

and when i run the program they give me this:

Exception in thread "main" java.lang.NullPointerException

at fortunewheel.Excel.EscreverExcel(Excel.java:79)
at fortunewheel.Excel.main(Excel.java:87)

What i did wrong? can u help me out?

Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
Madeira
  • 13
  • 5
  • 6
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – F. Lumnitz Feb 07 '17 at 14:46
  • 1
    which line is line no. 79? – Wasi Ahmad Feb 07 '17 at 14:51
  • The line 79 is: "sheet.getRow(0).createCell(2).setCellValue(Nome);" and the 87 is: "ex.EscreverExcel("Mário");" – Madeira Feb 07 '17 at 14:54

2 Answers2

0

OK, please check sheet.getRow(0) is not equal to null.

Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
MatWdo
  • 1,610
  • 1
  • 13
  • 26
0

Since you said, line no. 79 is the following line.

sheet.getRow(0).createCell(2).setCellValue(Nome);

My guess is, either sheet is a null object or, sheet.getRow() is returning null. I suggest you to check both of them to avoid null pointer exception.

From official documentation of XSSFSheet.getRow():

getRow() method returns the logical row ( 0-based). If you ask for a row that is not defined you get a null. This is to say row 4 represents the fifth row on a sheet.

Parameters:

rownum - row to get

Returns:

XSSFRow representing the rownumber or null if its not defined on the sheet

So my guess is, getRow() is returning null in your case.

Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161