3

I have got a csv file and I want import it into a JTable.

Is there a simple example showing how to import a csv file to JTable?

m1ddleware
  • 78
  • 2
  • 16
Lucy
  • 471
  • 4
  • 12
  • 28

3 Answers3

8

Use OpenCSV:

CSVReader reader = new CSVReader(new FileReader("yourfile.csv")); 
List myEntries = reader.readAll();
JTable table = new JTable(myEntries.toArray());
Rob
  • 435
  • 1
  • 5
  • 25
Timmo
  • 3,142
  • 4
  • 26
  • 43
5

the last answer didn't work for me because JTable wanted an Object[][] and a String[] (of column names)... I had to do something like this:

import com.opencsv.CSVReader;
import java.util.List;
import javax.swing.table.DefaultTableModel;
import javax.swing.JTable; 
import java.io.FileReader;

Object[] columnnames;
transient CSVReader CSVFileReader;
CSVFileReader = new CSVReader(new FileReader(csvFile));
List myEntries = CSVFileReader.readAll();
columnnames = (String[]) myEntries.get(0);
DefaultTableModel tableModel = new DefaultTableModel(columnnames, myEntries.size()-1); 
int rowcount = tableModel.getRowCount();
for (int x = 0; x<rowcount+1; x++)
{
    int columnnumber = 0;
    // if x = 0 this is the first row...skip it... data used for columnnames
    if (x>0)
    {
        for (String thiscellvalue : (String[])myEntries.get(x))
        {
            tableModel.setValueAt(thiscellvalue, x-1, columnnumber);
            columnnumber++;
        }
    }
}

JTable MyJTable = new JTable(tableModel);

Also if you want to retain backslash characters in your data, use this as a constructor:

CSVFileReader = new CSVReader(new FileReader(csvFile), ',', '"', '\0');

This sets "\0" to the escape character. Which I think sets the escape character to nothing. See this thread: opencsv in java ignores backslash in a field value

pcalkins
  • 1,188
  • 13
  • 20
-1

If you want / need to avoid CSVReader, you can also use BufferedReader. It is not as simple as CSVReader of course. You will definitely be able to improve it, as I am just a starter in Java file management.

This is partly borrowed from "JAVA IO - How To Import Text File Data To JTable In Java [ with source code ]" on https://www.youtube.com/watch?v=L2xczUN9aI0

import java.io.*;
import java.util.*;
import javax.swing.JTable;
import javax.swing.table.*;

public class Test {
    public static void main(String[] args) {
        String inputFileName;
        File inputFile;
        String firstRow;
        Vector<Vector<String>> vectorVectorStringsData = new Vector<Vector<String>>();
        Vector<String> vectorStrings = new Vector<String>();
        Vector<String> vectorColumnIdentifiers = new Vector<String>();
        String[] columnIdentifiers;
        DefaultTableModel model = new DefaultTableModel();
        JTable jTable;
        
        inputFileName = "yourFileName.csv";
        inputFile = new File(inputFileName);
        try (FileReader fr = new FileReader(inputFile);
            BufferedReader br = new BufferedReader(fr)) 
        {
            firstRow = br.readLine().trim();
            if (firstRow != null) {
                // headers:
                columnIdentifiers = firstRow.split(",");

                vectorColumnIdentifiers = new Vector<String>();
                for (int j =0; j < columnIdentifiers.length; j++) {
                    vectorColumnIdentifiers.add(columnIdentifiers[j]);
                }
            }
            // rows
            Object[] tableLines = br.lines().toArray();
            // data rows
            for (int i = 0; i < tableLines.length; i++) {
                System.out.println("4");
                String line = tableLines[i].toString().trim();
                String[] dataRow = line.split(",");
                vectorStrings = new Vector<String>();
                for (int j =0; j < dataRow.length; j++) {
                    vectorStrings.add(dataRow[j]);
                }
                vectorVectorStringsData.add(vectorStrings);
            }
            
            fr.close();
        }
        catch (IOException ioe) {
            System.out.println("error: " + ioe.getMessage());
        }

        model.setDataVector(vectorVectorStringsData, vectorColumnIdentifiers);
        jTable = new JTable(model);
    }
}
questionto42
  • 7,175
  • 4
  • 57
  • 90
  • In my case, I was obliged to use a data structure from the Collections Framewoek for didactical reasons. And in addition, I would not have been able to use OpenCSV because my AdoptOpenJdk does not seem to support it. – questionto42 Jun 22 '20 at 08:46
  • @kleopatra I do not know the conventions. Too new to Java, and not on it since long. I do not even remember having written this at all :). – questionto42 Sep 16 '22 at 12:52