import csv to JTable

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?


Solution 1:

Use OpenCSV:

CSVReader reader = new CSVReader(new FileReader("yourfile.csv")); 
List myEntries = reader.readAll();
JTable table = new JTable(myEntries.toArray());

Solution 2:

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