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

JavaCsvApache CommonsApache Commons-Csv

Java Problem Overview


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,rlee0@e-recht24.de
Bobby,Moreno,68 Dorton Avenue,Reno,AZ,79934,United States,5-(080)410-6743,bmoreno1@ihg.com
Eugene,Alexander,3 Bunker Hill Court,Newark,MS,30066,United States,5-(822)147-6867,ealexander2@gmpg.org
Katherine,Crawford,3557 Caliangt Avenue,New Orleans,OR,23289,United States,2-(686)178-7222,kcrawford3@symantec.com

It's located in my src folder.

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Solution 3 - Java

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;
             }
      }

Solution 4 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCreatureView Question on Stackoverflow
Solution 1 - JavafcuestaView Answer on Stackoverflow
Solution 2 - Javabiswajit khanView Answer on Stackoverflow
Solution 3 - JavaSanket MehtaView Answer on Stackoverflow
Solution 4 - Javauser14607302View Answer on Stackoverflow