我有一个csv文件.我想从中提取特定的列.例如:说,我有csv:
id1,caste1,salary,name1
63,Graham,101153.06,Abraham
103,Joseph,122451.02,Charlie
63,Webster,127965.91,Violet
76,Smith,156150.62,Eric
97,Moreno,55867.74,Mia
65,Reynolds,106918.14,Richard
Run Code Online (Sandbox Code Playgroud)
如何使用opencsv只读取头文件caste1中的数据?
Magnilex和Sparky是正确的,因为CSVReader不支持按列名读取值.但话说有两种方法可以做到这一点.
假设你有列名并且默认的CSVReader读取标题,你可以在第一个标题中搜索该位置,然后从那里开始使用它;
private int getHeaderLocation(String[] headers, String columnName) {
return Arrays.asList(headers).indexOf(columnName);
}
Run Code Online (Sandbox Code Playgroud)
所以你的方法看起来像(省去了很多需要放入的错误检查)
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
int columnPosition;
nextLine = reader.readNext();
columnPosition = getHeaderLocation(nextLine, "castle1");
while ((nextLine = reader.readNext()) != null && columnPosition > -1) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[columnPosition]);
}
Run Code Online (Sandbox Code Playgroud)
如果时间紧迫,我只会做上述事情而且你只关心一个专栏.这是因为openCSV可以直接转换为具有与标题列名相同的变量的对象,使用CsvToBean类和HeaderColumnNameMappingStrategy.
所以首先你要定义一个包含字段的类(实际上你只需要放入你想要的字段 - 额外的内容被忽略,缺少的是null或默认值).
public class CastleDTO {
private int id1;
private String castle1;
private double salary;
private String name1;
// have all the getters and setters here....
}
Run Code Online (Sandbox Code Playgroud)
然后你的代码看起来像
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
HeaderColumnNameMappingStrategy<CastleDTO> castleStrategy = new HeaderColumnNameMappingStrategy<CastleDTO>();
CsvToBean<CastleDTO> csvToBean = new CsvToBean<CastleDTO>();
List<CastleDTO> castleList = csvToBean.parse(castleStrategy, reader);
for (CastleDTO dto : castleList) {
System.out.println(dto.getCastle1());
}
Run Code Online (Sandbox Code Playgroud)
opencsv 中没有用于按名称读取列的内置功能。
该官方FAQ例如对如何从文件中读取下面的例子:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
}
Run Code Online (Sandbox Code Playgroud)
您只需通过访问行来获取每一行的第二列中的值nextLine[1](请记住,数组索引是从零开始的)。
因此,在您的情况下,您可以简单地从第二行读取:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
System.out.println(nextLine[1]);
}
Run Code Online (Sandbox Code Playgroud)
有关从其标题确定列索引的更复杂方法,请参阅Scott Conway 的答案。