import csv to JTable

后端 未结 3 506
终归单人心
终归单人心 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:43

    Use OpenCSV:

    CSVReader reader = new CSVReader(new FileReader("yourfile.csv")); 
    List myEntries = reader.readAll();
    JTable table = new JTable(myEntries.toArray());
    
    0 讨论(0)
  • 2020-12-01 20:47

    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);
        }
    }
    
    0 讨论(0)
  • 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; 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

    0 讨论(0)
提交回复
热议问题