我在写入 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
是一个 null 对象,或者 sheet.getRow()
返回 null。我建议您检查两者以避免空指针异常。
From official documentation of XSSFSheet.getRow():
getRow()
方法返回逻辑行(从 0 开始)。如果您请求未定义的行,则会得到空值。这就是说,第 4 行代表工作表上的第五行。
参数:
rownum - row to get
返回:
XSSFRow representing the rownumber or null if its not defined on the sheet
所以我的猜测是,在您的情况下,getRow()
返回 null。
关于java - Netbeans - Java Excel NullPointerExcepetion,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42092682/