Netbeans – Java Excel NullPointerExcepetion

我在写一个excel文件时遇到了问题。 我正在使用Apache POI写在Excel中。

我的代码是:

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"); } 

当我运行程序,他们给我这个:

 Exception in thread "main" java.lang.NullPointerException at fortunewheel.Excel.EscreverExcel(Excel.java:79) at fortunewheel.Excel.main(Excel.java:87) 

我做错了什么? 你能帮我吗?

既然你说,行号 79是以下行。

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

我的猜测是,无论是工作sheet是一个空对象或sheet.getRow()返回null。 我build议你检查它们,以避免空指针exception。

从XSSFSheet.getRow()的官方文档:

getRow()方法返回逻辑行(从0开始)。 如果你要求一个没有定义的行,你会得到一个空值。 这就是说,第4行代表了表单上的第五行。

参数:

 rownum - row to get 

返回:

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

所以我的猜测是, getRow()在你的情况下返回null。

好的,请检查sheet.getRow(0)是否等于null。