javaexcelvalidation

How can I check if the file is an excel file?


I'm writing a program, and the have to select an excel file, that will be read by the program. My question is now, how can I prove, if the file is an excel file or not?.

The file is selected in this method:

JButton btnFile = new JButton("Select Excel File");
btnFile.setPreferredSize(new Dimension(40, 40));
btnFile.addActionListener(new ActionListener() {
    // Handle open button action.
    public void actionPerformed(ActionEvent e) {
        final JFileChooser fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(frame);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            file = fc.getSelectedFile();
            // This is where a real application would open the file.
            System.out.println("File: " + file.getName() + ".");
        } else {
            System.out.println("Open command cancelled by user.");
        }
        System.out.println(returnVal);
    }
});

Solution

  • You can add a filter to the filechooser that only makes it possible to chose .xlsx files (you can add more extensions by using OR in the return with another extension)

        fc = new JFileChooser();
    
        fc.setFileFilter(new FileFilter() {
    
          public String getDescription() {
              return "Excel Documents (.xlsx)";
          }
    
          public boolean accept(File f) {
              if (f.isDirectory()) {
                  return true;
              } else {
                  String filename = f.getName().toLowerCase();
                  return filename.endsWith(".xlsx") ;
              }
          }
       });