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