0

I get an IOException with the code below. Whats the problem? What I want is to Read an Excel File xlsm and xls or xlsx via the filedialog after the import read the excel and work with it.

public class start {

public static void main(String[] args) throws IOException, InvalidFormatException {

    JFrame yourJFrame = new JFrame();
    FileDialog fd = new FileDialog(yourJFrame, "Choose a file", FileDialog.LOAD);
    fd.setVisible(true);
    String filename = fd.getFile();
    String filepth = fd.getDirectory();

    Workbook workbook = WorkbookFactory.create(new File(filepth + filename));

    System.out.println("Workbook has " + workbook.getNumberOfSheets() + " Sheets : ");
    Iterator<Sheet> sheetIterator = workbook.sheetIterator();
    System.out.println("Retrieving Sheets using Iterator");
    while (sheetIterator.hasNext()) {
        Sheet sheet = sheetIterator.next();
        System.out.println("=> " + sheet.getSheetName());
    }
String
    DataFormatter dataFormatter = new DataFormatter();

    System.out.println("\n\nIterating over Rows and Columns using Iterator\n");
    Iterator<Row> rowIterator = sheet.rowIterator();
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();

        Iterator<Cell> cellIterator = row.cellIterator();

        while (cellIterator.hasNext()) {
            Cell cell = cellIterator.next();
            String cellValue = dataFormatter.formatCellValue(cell);
            System.out.print(cellValue + "\t");
        }
        System.out.println();
    }

    workbook.close();
}
}
sharpnado
  • 79
  • 1
  • 1
  • 15
  • `JFileChooser` is the swing component to use instead of `FileDialog`(AWT). Not sure wether it should not be `new File(filepth + File.separator + filename)` – Joop Eggen Oct 09 '18 at 14:20
  • @JoopEggen I tried with JFileChooser but there is still a FileNotFoundException? – sharpnado Oct 09 '18 at 14:36
  • With JFileChooser, one uses `getSelectedFile()`. Example code should be in the www. However I do not see reading code. Check the web too. I have to be gone now. – Joop Eggen Oct 09 '18 at 14:43
  • 1
    `JFileChooser fc = new JFileChooser(); int rueckwrt = fc.showOpenDialog(null); if (rueckwrt == JFileChooser.APPROVE_OPTION) { String filename = fc.getSelectedFile().getName(); String filepth = fc.getSelectedFile().getPath(); System.out.println(filename);` this is what I did – sharpnado Oct 09 '18 at 14:44
  • Looks good. So the file was probably found in both ways, but apache-poi code is faulty. – Joop Eggen Oct 09 '18 at 14:46
  • it seems like the problem is with this line: `Workbook workbook = WorkbookFactory.create(new File(filepth + File.separator + filename));` – sharpnado Oct 09 '18 at 14:57

0 Answers0