2

我尝试了下面的代码,但不好,我无法创建 excel 文档,打开和关闭它。

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 创建 excel 文件的概念吗?

4

3 回答 3

3

这不会编译:

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 {
    }
}

在构造实例时实例化流。如果失败了,建筑也会失败。


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

于 2012-11-12T03:01:11.987 回答
3

您可以在子类中声明一个显式抛出 FileNotFoundException 的构造函数:

public Xls_Reader() throws FileNotFoundException {...} 

或者你用 try-catch 块包围你的基类中的代码,而不是抛出 FileNotFoundException 异常:

    FileInputStream fileOut = null;
    try { 
          FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
          // do something
        } 
   catch (FileNotFoundException ex) { ... } 
   finally {
        try 
        {
        // do something
            fileOut();
        } catch (IOException ex) {... }
    }  
于 2012-11-12T03:03:59.977 回答
1

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

  1. 使用 Apache POI 创建 Excel(.xlsx) 文档
  2. 使用 Apache POI 读写 Excel 文件
于 2012-11-12T03:05:05.910 回答