java 将 csv 导入 JTable
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10466079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
import csv to JTable
提问by Lucy
I have got a csv file and I want import it into a JTable.
我有一个 csv 文件,我想将它导入 JTable。
Is there a simple example showing how to import a csv file to JTable?
是否有一个简单的示例展示了如何将 csv 文件导入 JTable?
回答by DaTroop
Use OpenCSV:
使用 OpenCSV:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
List myEntries = reader.readAll();
JTable table = new JTable(myEntries.toArray());
回答by pcalkins
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:
最后一个答案对我不起作用,因为 JTable 想要一个 Object[][] 和一个 String[](列名)......我不得不做这样的事情:
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), ',', '"', '##代码##');
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”设置为转义字符。我认为这将转义字符设置为空。请参阅此线程:java 中的 opencsv 忽略字段值中的反斜杠