创buildexcel文件 – 编译错误

我试过下面的代码,但没有好的,我无法创buildExcel文档,打开和closures它。

package tests; import java.io.*; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.util.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class Xls_Reader { Workbook wb = new XSSFWorkbook(); FileOutputStream fileOut = new FileOutputStream("workbook.xlsx"); } 

我收到以下错误:

 Default constructor can not handle exception type FileNotFoundException thrown by implicit super constructor . Must define an explicit constructor. 

有人可以帮助我理解使用POI API创buildExcel文件的概念吗?

这些例子可以帮助你更好地理解

  1. 使用Apache POI创buildExcel(.xlsx)文档
  2. 使用Apache POI读写Excel文件

这不会编译:

 import java.io.*; public class Xls_Reader { FileOutputStream fileOut = new FileOutputStream("workbook.xlsx"); } 

但是这个修复了这个错误:

 import java.io.*; public class Xls_Reader { FileOutputStream fileOut = new FileOutputStream("workbook.xlsx"); public Xls_Reader() throws IOException { } } 

当实例正在构build时,stream被实例化。 如果失败了,build设也会如此。


顺便说一句 – 这是“Java 101”,与Apache POI无关。

要么在你的子类声明一个显式的构造函数抛出FileNotFoundException:

 public Xls_Reader() throws FileNotFoundException {...} 

或者使用try-catch块来代替基类中的代码,而不是引发FileNotFoundExceptionexception:

  FileInputStream fileOut = null; try { FileOutputStream fileOut = new FileOutputStream("workbook.xlsx"); // do something } catch (FileNotFoundException ex) { ... } finally { try { // do something fileOut(); } catch (IOException ex) {... } }