【问题标题】:Create excel file - compilation error创建excel文件 - 编译错误
【发布时间】:2012-11-12 02:49:13
【问题描述】:

我尝试了下面的代码但是不行,我无法创建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 文件的概念吗?

【问题讨论】:

    标签: java excel compilation compiler-errors apache-poi


    【解决方案1】:

    这不会编译:

    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 无关。

    【讨论】:

      【解决方案2】:

      要么在子类中声明一个显式抛出 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) {... }
          }  
      

      【讨论】:

      • +1 表示“更好的异常处理”。我的例子只是“把滴答作响的炸弹扔给下一个傻瓜”。 ;)
      【解决方案3】:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多