import csv to JTable

后端 未结 3 523
终归单人心
终归单人心 2020-12-01 20:16

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?

3条回答
  •  我在风中等你
    2020-12-01 20:52

    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; x0)
        {
            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

提交回复
热议问题