Jxl NullPointerException与workbook.close()方法

我试图写一个excel文件,但我遇到了两个问题。 这是相关的代码:

public ExcelFormWriter() throws IOException, WriteException{ setOutputFile("DataAnalysis.xls"); File file = new File(inputFile); WorkbookSettings wbSettings = new WorkbookSettings(); wbSettings.setLocale(new Locale("en", "EN")); workbook = Workbook.createWorkbook(file, wbSettings); workbook.createSheet("RawData", 0); } public void addLabel(int column, int row, String s) throws WriteException, RowsExceededException, IOException { excelSheet = workbook.getSheet(0); createLabel(excelSheet); Label label = new Label(column, row, s, times); excelSheet.addCell(label); workbook.write(); workbook.close(); } 

在另一个class里,我这样称呼:

  ExcelFormWriter test = new ExcelFormWriter(); int row = 1; for (int i = 100; i > 0; i--){ test.addLabel(0,row,getDateNDaysAgo(i)); row++; } 

如果我像这样运行它,它将第一行写入excel文件,然后返回一个NullPointerException。

我发现,如果我注释掉“workbook.close()”,它通过for循环运行,并且构build成功完成,但是当我查看excel文件时,实际上没有任何内容写入。

我对写电子表格并不是很熟悉,所以很可能是我的代码有一个基本的缺陷,比如某个地方出了问题。 任何答案是赞赏,但请具体在你的答案,因为我感觉在这个代码在黑暗中,我不知道什么是什么。

未来的诊断/这个东西的故障排除build议也将不胜感激。

UPDATE

我已经提供了closures工作簿的一个单独的方法。 谢谢你的提示。 但是,第二个问题依然存在。 只有电子表格的第一行被写入。

  public void close() throws IOException, WriteException{ workbook.close(); } 

这就是我所说的方法。 也许有一个问题呢?

 int row = 1; for (int i = 100; i > 0; i--){ test.addLabel(0,row,getDateNDaysAgo(i)); row++; } test.close(); 

您必须将workbook.close()语句放在addLabel函数之外,因为您正在for循环的第一次迭代中调用它,closures工作簿,然后在下一次迭代中尝试写入到不再现有的工作簿。 添加一个closeWorkbook函数或由getter调用工作簿,并在写入单元格后closures它。