Java 未指定标头映射,无法按名称访问记录值 (Apache Commons CSV)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27323639/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:10:34  来源:igfitidea点击:

No header mapping was specified, the record values can't be accessed by name (Apache Commons CSV)

javacsvapache-commonsapache-commons-csv

提问by Creature

I got this error message happening when I'm trying to read a csv:

我在尝试读取 csv 时收到此错误消息:

Exception in thread "main" java.lang.IllegalStateException: No header mapping was specified, the record values can't be accessed by name
at org.apache.commons.csv.CSVRecord.get(CSVRecord.java:99)
at mockdata.MockData.main(MockData.java:33)

Java Result: 1

Java 结果:1

I'm using Apache Commons CSV library 1.1. Tried googling the error message and the only thing I get is the code listing on sites like grepcode.

我正在使用 Apache Commons CSV 库 1.1。尝试使用谷歌搜索错误消息,我得到的唯一结果是 grepcode 等网站上的代码列表。

Here's my code:

这是我的代码:

package mockdata;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;

public class MockData
{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws FileNotFoundException, IOException
    {
        Reader in = new InputStreamReader(MockData.class.getClassLoader()
                                .getResourceAsStream("MOCK_DATA.csv"), "UTF-8");
        Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
        for (CSVRecord record : records) 
        {
            String lastName = record.get("last_name");
            String firstName = record.get("first_name");

            System.out.println("firstName: " + firstName + " lastName: " + lastName);
        }
    }

}

The contents of CSV:

CSV 的内容:

first_name,last_name,address1,city,state,zip,country,phone,email
Robin,Lee,668 Kinsman Road,Hagerstown,TX,94913,United States,5-(078)623-0713,[email protected]
Bobby,Moreno,68 Dorton Avenue,Reno,AZ,79934,United States,5-(080)410-6743,[email protected]
Eugene,Alexander,3 Bunker Hill Court,Newark,MS,30066,United States,5-(822)147-6867,[email protected]
Katherine,Crawford,3557 Caliangt Avenue,New Orleans,OR,23289,United States,2-(686)178-7222,[email protected]

It's located in my src folder.

它位于我的 src 文件夹中。

采纳答案by fcuesta

Calling withHeader() to the default Excel CSV format worked for me:

调用 withHeader() 到默认的 Excel CSV 格式对我有用:

CSVFormat.EXCEL.withHeader().parse(in);

The sample in the documentation is not very clear, but you can found it here: Referencing columns safely:If your source contains a header record, you can simplify your code and safely reference columns, by using withHeader(String...) with no arguments: CSVFormat.EXCEL.withHeader();

文档中的示例不是很清楚,但您可以在此处找到 : 安全地引用列:如果您的源包含标题记录,则可以通过使用 withHeader(String...) 来简化代码并安全地引用列参数:CSVFormat.EXCEL.withHeader();

回答by biswajit khan

this worked for me

这对我有用

try (Reader in = new FileReader(f);
                CSVParser parser = new CSVParser(in,
                        CSVFormat.EXCEL.withDelimiter(';').withHeader("Assembly Item Number", "Material Type",                              "Item Name", "Drawing Num", "Document Type", "Revision", "Status", "Drawing name",
                                "BOM Material Type", "Component Name"));) {
            for (CSVRecord record : parser) {
                    System.out.println(record.get("Item Name"));
            }
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }