2012-05-05 131 views
1

我有一個csv文件我想將它導入到一個JTable。導入csv到JTable

是否有一個簡單的例子顯示如何將csv文件導入到JTable?

回答

6

使用OpenCSV:

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

謝謝,它的工作。 – Lucy

+0

歡迎您! – DaTroop

4

最後的答案並沒有爲我工作,因爲JTable中想我有一個Object [] []和一個String [](列名)... 做是這樣的:

Object[] columnnames; 
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); 

此外,如果你想保留反斜槓字符在您的數據,以此作爲一個構造函數:

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

這將「\ 0」設置爲轉義字符。我認爲,這種逃生角色並沒有任何意義。看到這個線程:opencsv in java ignores backslash in a field value

+0

你用什麼進口? – TheCrazyProfessor

+0

import com.opencsv.CSVReader; import java.util.List; import javax.swing.table.DefaultTableModel; import javax.swing.JTable; – pcalkins