[英]How to read csv since header inclusively in apache commons csv?
以下方法允许使用跳过标题读取:
Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(in);
for (CSVRecord record : records) {
//here first record is not header
}
我怎样才能读取 csv 因为包含标题行?
聚苯乙烯
方法:
CSVFormat.EXCEL.withHeader().withSkipHeaderRecord(false).parse(in)
不起作用并且具有相同的行为
对我来说,以下所有内容似乎都将标题记录作为第一个记录(使用commons-csv
1.5):
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
Iterable<CSVRecord> records = CSVFormat.EXCEL.withSkipHeaderRecord().parse(in); //???
Iterable<CSVRecord> records = CSVFormat.EXCEL.withSkipHeaderRecord(false).parse(in);
Iterable<CSVRecord> records = CSVFormat.EXCEL.withSkipHeaderRecord(true).parse(in); //???
正如您所说,以下似乎没有将标题记录作为第一个记录:
Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(in); //???
我无法理解为什么withSkipHeaderRecord()
和withSkipHeaderRecord(true)
确实包含标题而withHeader()
不包含; 似乎与方法名称所暗示的行为相反。
withHeader()
方法告诉解析器文件有一个标题。 也许方法名称令人困惑。
withFirstRecordAsHeader()
方法也可能有用。
从CSVFormat (Apache Commons CSV 1.8 API) JavaDoc 页面:
安全地引用列
如果您的源包含标题记录,您可以通过使用不带参数的
withHeader(String...)
来简化代码并安全地引用列:CSVFormat.EXCEL.withHeader();
这会导致解析器读取第一条记录并将其值用作列名。 然后,调用采用 String 列名称参数的
CSVRecord
get 方法之一:String value = record.get("Col1");
这使您的代码不受 CSV 文件中列顺序更改的影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.