How to import a csv file to a Jtable?

Asked

Viewed 316 times

-1

Does anyone know how to move from a csv file to a jtable? Currently but lists 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();
        }
    }
  • 1

    Add a [mcve] of your code and an example excerpt of your csv data so that it is possible to simulate the problem.

  • Usually csv files come unstopped by a dot and comma (;) or other delimiting character. Break the string by the delimiter inside the while and then mount the string array with the broken values so that each one is in a cell of the table.

  • can show an example @Wagnersoares ?

1 answer

0

Alter your while so, supposing that your .csv either with 3 columns and separated by a point and comma (data 1;data 2;data 3)

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 couldn’t test it here at work, but it should work.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.