Ugur Tufekci
Ugur Tufekci

Reputation: 350

JFileChooser and Reading from Excel File using JAVA

I have a following code

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.text.html.HTMLDocument.Iterator;

    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Workbook;

  public class ExcelRead {
       public static String keep = "";

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

    // File Openner
    JFrame.setDefaultLookAndFeelDecorated(true);
    JDialog.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("JComboBox Test");
    frame.setLayout(new FlowLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JButton button = new JButton("Select File");

    button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent ae) {
            JFileChooser fileChooser = new JFileChooser();
            int returnValue = fileChooser.showOpenDialog(null);
            if (returnValue == JFileChooser.APPROVE_OPTION) {
                File selectedFile = fileChooser.getSelectedFile();

                keep = selectedFile.getName();
                System.out.println(keep);
            }
        }
    });
    frame.add(button);
    frame.pack();
    frame.setVisible(true);
    // end of the File opener
    // read from excel
    File excel = new File(keep);

    FileInputStream fis = new FileInputStream(excel);
    HSSFWorkbook wb = new HSSFWorkbook(fis);


    String sheetName = "Assignments"; //if my tempsheet start with "sheetname" thats okay

    for (int i = 0; i < wb.getNumberOfSheets() - 1; i++) {
        HSSFSheet tmpSheet = wb.getSheetAt(i);
        if (tmpSheet.getSheetName().startsWith(sheetName)) {
            //satırları ve sutunları gez oku

        } else {
                wb.removeSheetAt(i);
            }

        }


    }// end of the main




private static String cellToString(HSSFCell cell) {
    int type;
    Object result;
    type = cell.getCellType();
    switch (type) {
    case 0:
        result = cell.getNumericCellValue();
        break;
    case 1:
        result = cell.getStringCellValue();
        break;
    default:
        throw new RuntimeException("there are no support for this type of cell");
    }

    return result.toString();
}
       }

The problem is,I got exception when I run this code before choosing a file. I want to choose a file with FileChooser then I return that file name for reading from excel file. Output:

 Exception in thread "main" java.io.FileNotFoundException: 
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at ExcelRead.main(ExcelRead.java:54)

Upvotes: 0

Views: 3053

Answers (2)

Piyush Mittal
Piyush Mittal

Reputation: 1890

the problem is with

 public static String keep ="";

when file input stream comes at FileInputStream fis = new FileInputStream(excel);

it gets excel which has no file location; and throws you the exception.

File excel = new File(keep);
FileInputStream fis = new FileInputStream(excel);

handle public static String keep =""; as per your requirement :)

Upvotes: 0

Alex Fargus
Alex Fargus

Reputation: 122

The FileNotFound exception is due to the value of keep still being "" at the time you try to read the file.

This is because the code where you set the value of keep is in an ActionListener on the button. The action that will trigger this code (most likely a button press) has not occurred yet.

Try this:

public static void chooseFile() {
    JFileChooser fileChooser = new JFileChooser();
    int returnValue = fileChooser.showOpenDialog(null);
    if (returnValue == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fileChooser.getSelectedFile();

        keep = selectedFile.getName();
        System.out.println(keep);
    }
}
public static void main(String[] args) throws IOException {

// File Openner
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("JComboBox Test");
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Select File");

button.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent ae) {
        chooseFile()
    }
});
frame.add(button);
frame.pack();
frame.setVisible(true);
// end of the File opener
// read from excel

chooseFile() // <- make sure that the file is chosen

File excel = new File(keep);

FileInputStream fis = new FileInputStream(excel);
HSSFWorkbook wb = new HSSFWorkbook(fis);


String sheetName = "Assignments"; //if my tempsheet start with "sheetname" thats okay

for (int i = 0; i < wb.getNumberOfSheets() - 1; i++) {
    HSSFSheet tmpSheet = wb.getSheetAt(i);
    if (tmpSheet.getSheetName().startsWith(sheetName)) {
        //satırları ve sutunları gez oku

    } else {
            wb.removeSheetAt(i);
        }

    }


}// end of the main

Upvotes: 1

Related Questions