How to import a csv file into a JTable?

-1

Does anyone know how to move from a csv file to a jtable? At the moment but list everything in the first column.

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();

        try {
           File file = new File("Users.csv");
           if (!file.exists()) {
            file.createNewFile();
        }

           FileReader fr = new FileReader(file.getAbsoluteFile());
           BufferedReader br = new BufferedReader(fr);

           String line;


           while ((line = br.readLine()) != null) {
                model.addRow(new String[] {line});



            }
           br.close();
           fr.close();

        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
    
asked by anonymous 16.02.2017 / 18:32

1 answer

0

Change your while so, assuming your .csv is with 3 columns and separated by semicolons (data1, data2, data3)

while ((line = br.readLine()) != null) {
      //estou dividindo em um array quebrando a linha pelos ponto e virgula
      String colunas[] = line.split(";");

      //passo para o model cada item da linha separadamente
      model.addRow(new String[] {colunas[0], colunas[1], colunas[2]});

}

I did not have to test here at work, but it should work.

    
17.02.2017 / 16:46