使用 apache commons 获取 CSV 文件 header

Get CSV file header using apache commons

我一直在寻找过去 2 小时的问题解决方案,但徒劳无功。我正在尝试使用 Apache commons 读取 CSV 文件,我能够读取整个文件,但我的问题是如何仅提取数组中 CSV 的 header?

默认情况下,CSVParser 读取的第一条记录将始终是 header 记录,例如在下面的例子中:

CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER_MAPPING);
FileReader fileReader = new FileReader("file");
CSVParser csvFileParser = new CSVParser(fileReader, csvFileFormat);
List csvRecords = csvFileParser.getRecords();

csvRecords.get(0) 将 return header 记录。

我到处都看了,甚至上面的解决方案也没有用。 对于遇到此问题的任何其他人,确实如此。

Iterable<CSVRecord> records;
Reader in = new FileReader(fileLocation);
records = CSVFormat.EXCEL.withHeader().withSkipHeaderRecord(false).parse(in);
Set<String> headers = records.iterator().next().toMap().keySet();

请注意,您对 .next() 的使用占用了 CSV 的一行。

BufferedReader br = new BufferedReader(new FileReader(filename));

CSVParser parser = CSVParser.parse(br, CSVFormat.EXCEL.withFirstRecordAsHeader());

List<String> headers = parser.getHeaderNames();

这对我有用。最后一行是您需要的,将解析器找到的 headers 提取到字符串列表中。

在 Kotlin 中:

val reader = File(path).bufferedReader()
val records = CSVFormat.DEFAULT.withFirstRecordAsHeader()
    .withIgnoreHeaderCase()
    .withTrim()
    .parse(reader)

println(records.headerNames)

下面的代码对我有用:

import java.io.FileReader;
import org.apache.commons.csv.*;

public static String[] headersInCSVFile (String csvFilePath) throws IOException {
        //reading file
        CSVFormat csvFileFormat = CSVFormat.DEFAULT;
        FileReader fileReader = new FileReader(csvFilePath);
        CSVParser csvFileParser = new CSVParser(fileReader, csvFileFormat);
        List csvRecords = csvFileParser.getRecords();
        
        //Obtaining first record and splitting that into an array using delimiters and removing unnecessary text
        String[] headers = csvRecords.get(0).toString().split("[,'=\]\[]+");
        String[] result = new String[headers.length - 6];
        for (int i = 6; i < headers.length; i++) {
            //.replaceAll("\s", "") removes spaces
            result[i - 6] = headers[i].replaceAll("\s", "");
        } 
        return result;
}

自 Apache Commons CSV v1.9.0 起,withSkipHeaderRecord()withFirstRecordAsHeader() 方法已弃用。提供了构建器界面。如此使用它:

CSVFormat.DEFAULT.builder()
    .setHeader()
    .setSkipHeaderRecord(true)
    .build();