1

以下方法允许使用跳过标题进行读取:

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)

不起作用并且具有相同的行为

4

2 回答 2

3

对我来说,以下所有似乎都将标题记录作为第一个(使用commons-csv1.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()没有;似乎与方法名称所暗示的行为相反。

于 2017-11-09T16:12:13.817 回答
1

withHeader()方法告诉解析器该文件有一个标题。也许方法名称令人困惑。

withFirstRecordAsHeader()方法也可能有用。

CSVFormat(Apache Commons CSV 1.8 API) JavaDoc 页面:

安全地引用列

如果您的源代码包含标题记录,则可以通过withHeader(String...)不带参数使用来简化代码并安全地引用列:

CSVFormat.EXCEL.withHeader();

这会导致解析器读取第一条记录并将其值用作列名。然后,调用CSVRecord采用 String 列名参数的 get 方法之一:

String value = record.get("Col1");

这使您的代码不受 CSV 文件中列顺序更改的影响。

于 2021-01-27T14:51:34.047 回答