Csv import into JTable

I have a csv file, I want to import it into JTable.

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

+1


source to share


2 answers


Use OpenCSV:



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

      

+6


source


the last answer didn't work for me because the JTable wanted Object [] [] and String [] (on behalf of the column) ... 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 keep backslashes in your data use this as a constructor:



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

      

This sets "\ 0" to the escape character. Which, I guess, does not control anything with the escape symbol. See this thread: opencsv in java ignores backslashes in field value

+4


source







All Articles