Madeira Madeira - 1 year ago 117
Java Question

Netbeans - Java Excel NullPointerExcepetion

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download