[英]Netbeans - Java Excel NullPointerExcepetion
I'm having a problem with writing in a excel file. 我在excel文件中写入时遇到问题。 I'm using Apache POI to write on the excel. 我正在使用Apache POI在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? 你能救我吗?
好的,请检查sheet.getRow(0)不等于null。
Since you said, line no. 既然你说,行号。 79 is the following line. 79是以下行。
sheet.getRow(0).createCell(2).setCellValue(Nome);
My guess is, either sheet
is a null object or, sheet.getRow()
is returning null. 我的猜测是, sheet
是一个null对象,或者sheet.getRow()
返回null。 I suggest you to check both of them to avoid null pointer exception. 我建议你检查它们以避免空指针异常。
From official documentation of XSSFSheet.getRow() : 从XSSFSheet.getRow()的官方文档:
getRow()
method returns the logical row ( 0-based). getRow()
方法返回逻辑行(从0开始)。 If you ask for a row that is not defined you get a null. 如果您要求未定义的行,则会得到null。 This is to say row 4 represents the fifth row on a sheet. 这就是说第4行代表工作表上的第五行。
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. 所以我的猜测是, getRow()
在你的情况下返回null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.