MKod
MKod

Reputation: 823

Create excel file - compilation error

I tried below code but no good, I am unable to create excel document, open and close it.

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");

}

I am getting following error:

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

Can someone help me understand the concept of creating excel file with POI API?

Upvotes: 2

Views: 406

Answers (3)

dreamcrash
dreamcrash

Reputation: 51433

Either you declare a constructor at your subclass that explicitly throws FileNotFoundException:

public Xls_Reader() throws FileNotFoundException {...} 

Or you surround the code in your base class with a try-catch block instead of throwing a FileNotFoundException exception:

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

Upvotes: 3

Maxi Baez
Maxi Baez

Reputation: 578

These examples can help you to understand better

  1. Create Excel(.xlsx) document using Apache POI
  2. Read and write Excel file using Apache POI

Upvotes: 1

Andrew Thompson
Andrew Thompson

Reputation: 168825

This will not compile:

import java.io.*;

public class Xls_Reader  {

    FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
}

But this fixes the error:

import java.io.*;

public class Xls_Reader  {

    FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");

    public Xls_Reader() throws IOException {
    }
}

The stream is instantiated as the instance is being constructed. If it fails, so will the construction.


BTW - this is 'Java 101' and has nothing to do with Apache POI.

Upvotes: 3

Related Questions