将CSV文件导入JTable

时间:2016-09-22 06:22:40

标签: java user-interface

目前有一张桌子显示我作为一个小项目制作的应用程序的ID,位置,状态和患者。我正在尝试将CS​​V文件(不使用CSV阅读器)导入此表,但遇到了困难。

table = new JTable();
table.setModel(new DefaultTableModel(
    new Object[][] {
    },
    new String[] {
        "ID", "Location", "Status", "Patient"
    }
));
scrollPane.setViewportView(table);
contentPane.setLayout(gl_contentPane);

2 个答案:

答案 0 :(得分:0)

使用OpenCSV:

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

答案 1 :(得分:0)

试试这个。

static Object[][] readCsv(String file) throws IOException {
    List<Object[]> lines = new ArrayList<>();
    try (BufferedReader r = new BufferedReader(new FileReader(file))) {
        String line;
        while ((line = r.readLine()) != null)
            lines.add(line.split(","));
    }
    return lines.toArray(new Object[lines.size()][]);
}

    JTable table = new JTable();
    table.setModel(new DefaultTableModel(
        readCsv("data/test.csv"),
        new String[] {
            "ID", "Location", "Status", "Patient"
        }
    ));