0

so I'm in the process of trying to learn Apache's POI API and I'm having a little difficulty understanding something. I'm trying to open an existing Excel File using the JFileChooser class, so that the user selects the Excel file and then I'll modify it a certain way. I'm having issues opening the file though. It keeps giving me this error: Unreported Exception. Must be caught or declared to be thrown at the line that has XSSFWorkbook code. My logic is as follows:

1) Have the user select the excel file they want to modify by using the JFileChooser Class

2) Create a new workbook and sheet to transfer that data from the chosen excel file

3) modify data

public class readInExcel {
static void readExcel() throws IOException
{

    JFileChooser fileChooser = new JFileChooser();

    fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));

    int returnVal = fileChooser.showOpenDialog(new JPanel());

    if(returnVal == JFileChooser.APPROVE_OPTION)
    {   
        File OGFile = fileChooser.getSelectedFile();

        String fileName = "user.home.Desktop";
        XSSFWorkbook wb = new XSSFWorkbook(OGFile);


        XSSFSheet sheet = wb.createSheet("FirstSheet");


        }   

}
humbleCoder
  • 463
  • 1
  • 5
  • 18

1 Answers1

2

Unreported Exception Error means that you are calling a method that could possibly throw an exception and needs to be handled. In this case, you would need to either put that method around a try-catch block to catch the exception or throw it so it could be handled by something else.

Apologies, I just noticed you handled the IOException. The other error you are getting is the RuntimeException. This exception is thrown from when you create the XSSFWorkbook object. The parameter you are putting in the constructor is of type File when it requires a type InputStream or OPCPackage. Just create a FileInputStream like so:

InputStream is = new FileInputStream(OGFile);
XSSFWorkbook wb = new XSSFWorkbook(is);

Then you should not have anymore unhandled/thrown errors.

  • Yes! Thank you so much! – humbleCoder Mar 25 '17 at 17:44
  • One more question. Is there a way to print the contents of the excel file to the console? – humbleCoder Mar 25 '17 at 17:51
  • What kind of contents? Like to check if a file is null? There are methods to obtain information which you may put into the console such as a specific cell's background/foreground color via rgb values. You can also iterate through the row/columns to obtain the cell's written contents and display that. My preference is to write it in an output file via outputstream – Andrew Hyun Mar 25 '17 at 18:24