0

I'm trying to upload an Excel file .xls to my MySQL Database using Java NetBeans but I didn't find any solution.

I tried with CSV file and it worked fine, but I would still like to use the .xls file format.

To achieve this I want the user to click a JButton in my JFrame, choose an Excel file by using JFileChooser and then save that file in my database.

Following is the image of what I currently have: JFrame image

And this is the code I used so far:

private void importer_csv_btnActionPerformed(java.awt.event.ActionEvent evt) {
    JFileChooser chooser = new JFileChooser();
    chooser.showOpenDialog(null);
    File f = chooser.getSelectedFile();
    String filename = f.getAbsolutePath();
    import_interne_txt.setText(filename);

    try {

        BufferedReader br = new BufferedReader(new FileReader(filename));
        String line;
        while ((line = br.readLine()) != null) {
            String[] value = line.split(",");
            String sql = "INSERT INTO Interne(Matricule,Nom,Prénom,Sexe,Date_naissance,Nationalité,Lieu_naissance,Willaya,Email,Moyenne1,Moyenne2,Redoublement,Conseil,Num_Phone,Password,CPI_Code) " + "VALUES('" + value[0] + "','" + value[1] + "','" + value[2] + "','" + value[3] + "','" + value[4] + "','" + value[5] + "','" + value[6] + "','" + value[7] + "','" + value[8] + "','" + value[9] + "','" + value[10] + "','" + value[11] + "','" + value[12] + "','" + value[13] + "','" + value[14] + "','" + value[15] + "')";
            pst = Con.prepareStatement(sql);
            pst.executeUpdate();

        }
        br.close();
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
    Update_table();
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Possible duplicate of [How to read and write excel file in java](http://stackoverflow.com/questions/1516144/how-to-read-and-write-excel-file-in-java) – Fruchtzwerg Apr 22 '16 at 16:16

1 Answers1

0

Use Apache POI to read data from xls files.

Example:

public extractDataFromXls(String fileName, sheetName) throws FileNotFoundException {
        FileInputStream fileInputStream = new FileInputStream(fileName);
        HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
        HSSFSheet worksheet = workbook.getSheet(sheetName);
        HSSFRow row = worksheet.getRow(0);
        for (short i = 0; i < 5; i++) {
            HSSFCell cell = row.getCell(i);
            String value = cell.getStringCellValue();
            System.out.println(value);
        }
    }
Adnan Isajbegovic
  • 2,227
  • 17
  • 27