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

5

59

I got this error message happening when I'm trying to read a 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

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.

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:

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.

Alaynaalayne answered 5/12, 2014 at 19:53 Comment(0)
P
90

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

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();

Phyllida answered 12/12, 2014 at 16:30 Comment(4)
The commons csv user guide example is just plain wrong. About par for the course for open source projects. commons.apache.org/proper/commons-csv/user-guide.htmlWilli
with version 1.9.0 withHeader() is now deprecated and the guide hasn't been updated. You're supposed to use this pattern: CSVFormat.RFC4180.builder().setHeader("a","b","c").build().parse(in)Amadoamador
If you want automatic discovery of the headers instead of specifying them yourself, CSVFormat.RFC4180.builder().setHeader().setSkipHeaderRecord(true).build() also works.Minsk
@ØysteinØvrebø For some reason I was not able to read the first column value. Is there a known issueOccasionalism
A
3

With version 1.9.0 withHeader() is now deprecated and the guide hasn't been updated. You're supposed to use this pattern: CSVFormat.RFC4180.builder().setHeader("a","b","c").build().parse(in)

Amadoamador answered 9/9, 2022 at 20:33 Comment(0)
B
2

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();
        }
Bucolic answered 2/12, 2019 at 10:20 Comment(0)
P
0

I managed to ignore the space in the header name (in between) using the following code - by using the get(index) instead of get("header_name"). And also, stop reading the csv when blank value/row is detected:

 CSVParser csvParser = CSVFormat.EXCEL.withFirstRecordAsHeader().parse(br);
         for (CSVRecord record : csvParser) {
             String number= record.get(0);
             String date = record.get("date");
             String location = record.get("Location");
             String lsFile = record.get(3);
             String docName = record.get(4);
          
             
             if(StringUtils.isEmpty(lsFile)) {
                 break;
             }
      }
Pantograph answered 17/7, 2020 at 10:2 Comment(0)
A
0

you need to get a look a the definition of every format in this URL to define the format of your file try this :

      File f = new File("your path file ");
      Reader  readfile = new FileReader(f);

    Iterable<CSVRecord> records = CSVFormat.DEFAULT.withDelimiter(';').withHeader().parse(readfile);
Aleta answered 9/11, 2020 at 16:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.