The Wayback Machine - https://web.archive.org/web/20240811155526/https://www.geeksforgeeks.org/mapping-csv-to-javabeans-using-opencsv/
Open In App

Mapping CSV to JavaBeans Using OpenCSV

Last Updated : 05 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

OpenCSV provides classes to map CSV file to a list of Java-beans. CsvToBean class is used to map CSV data to JavaBeans. The CSV data can be parsed to a bean, but what is required to be done is to define the mapping strategy and pass the strategy to CsvToBean to parse the data into a bean. HeaderColumnNameTranslateMappingStrategy is the mapping strategy which maps the column id to the java bean property.

  1. First add OpenCSV to the project.
    • For maven project, include the OpenCSV maven dependency in pom.xml file. 

xml




<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>4.1</version>
</dependency>


  • For Gradle Project, include the OpenCSV dependency.
compile group: 'com.opencsv', name: 'opencsv', version: '4.1'
  • You can Download OpenCSV Jar and include in your project class path.
  1. Mapping CSV to JavaBeans Mapping a CSV to JavaBeans is simple and easy process. Just follow these couple of steps:
    1. Create a Hashmap with mapping between the column id and bean property.
Map mapping = new HashMap();
        mapping.put("column  id ", "javaBeanProperty");
  1. Then add all the column id of csv file with their corresponding javabean property.
  2. Create HeaderColumnNameTranslateMappingStrategy object pass mapping hashmap to setColumnMapping method.
HeaderColumnNameTranslateMappingStrategy strategy =
 new HeaderColumnNameTranslateMappingStrategy();
        strategy.setType(JavaBeanObject.class);
        strategy.setColumnMapping(mapping);
  1. Create the object of CSVReader and CsvToBean class
String csvFilename = "data.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
CsvToBean csv = new CsvToBean();
  1. Call parse method of CsvToBean class and pass HeaderColumnNameTranslateMappingStrategy and CSVReader objects.
List list = csv.parse(strategy, csvReader);

Example: Let’ s convert csv file containing Student data to Student objects having attribute Name, RollNo, Department, Result, Pointer.

StudentData.csv:

name, rollno, department, result, cgpa
amar, 42, cse, pass, 8.6
rohini, 21, ece, fail, 3.2
aman, 23, cse, pass, 8.9
rahul, 45, ee, fail, 4.6
pratik, 65, cse, pass, 7.2
raunak, 23, me, pass, 9.1
suvam, 68, me, pass, 8.2

First create a Student Class with Attributes Name, RollNo, Department, Result, Pointer. Then Create a main class which map csv data to JavaBeans object. Programs:

  1. Student.java 

Java




public class Student {
    private static final long serialVersionUID = 1L;
 
    public String Name, RollNo, Department, Result, Pointer;
 
    public String getName()
    {
        return Name;
    }
 
    public void setName(String name)
    {
        Name = name;
    }
 
    public String getRollNo()
    {
        return RollNo;
    }
 
    public void setRollNo(String rollNo)
    {
        RollNo = rollNo;
    }
 
    public String getDepartment()
    {
        return Department;
    }
 
    public void setDepartment(String department)
    {
        Department = department;
    }
 
    public String getResult()
    {
        return Result;
    }
 
    public void setResult(String result)
    {
        Result = result;
    }
 
    public String getPointer()
    {
        return Pointer;
    }
 
    public void setPointer(String pointer)
    {
        Pointer = pointer;
    }
 
    @Override
    public String toString()
    {
        return "Student [Name=" + Name + ", RollNo=" + RollNo + ",
            Department
            = " + Department + ",
            Result = " + Result
                     + ", Pointer=" + Pointer + "]";
    }
}


  1. csvtobean.java 

Java




import java.io.*;
import java.util.*;
 
import com.opencsv.CSVReader;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.HeaderColumnNameTranslateMappingStrategy;
 
public class csvtobean {
    public static void main(String[] args)
    {
 
        // Hashmap to map CSV data to
        // Bean attributes.
        Map<String, String> mapping = new
                      HashMap<String, String>();
        mapping.put("name", "Name");
        mapping.put("rollno", "RollNo");
        mapping.put("department", "Department");
        mapping.put("result", "Result");
        mapping.put("cgpa", "Pointer");
 
        // HeaderColumnNameTranslateMappingStrategy
        // for Student class
        HeaderColumnNameTranslateMappingStrategy<Student> strategy =
             new HeaderColumnNameTranslateMappingStrategy<Student>();
        strategy.setType(Student.class);
        strategy.setColumnMapping(mapping);
 
        // Create csvtobean and csvreader object
        CSVReader csvReader = null;
        try {
            csvReader = new CSVReader(new FileReader
            ("D:\\EclipseWorkSpace\\CSVOperations\\StudentData.csv"));
        }
        catch (FileNotFoundException e) {
 
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        CsvToBean csvToBean = new CsvToBean();
 
        // call the parse method of CsvToBean
        // pass strategy, csvReader to parse method
        List<Student> list = csvToBean.parse(strategy, csvReader);
 
        // print details of Bean object
        for (Student e : list) {
            System.out.println(e);
        }
    }
}


Output:

Student [Name=amar, RollNo=42, Department=cse, Result=pass, Pointer=8.6]
Student [Name=rohini, RollNo=21, Department=ece, Result=fail, Pointer=3.2]
Student [Name=aman, RollNo=23, Department=cse, Result=pass, Pointer=8.9]
Student [Name=rahul, RollNo=45, Department=ee, Result=fail, Pointer=4.6]
Student [Name=pratik, RollNo=65, Department=cse, Result=pass, Pointer=7.2]
Student [Name=raunak, RollNo=23, Department=me, Result=pass, Pointer=9.1]
Student [Name=suvam, RollNo=68, Department=me, Result=pass, Pointer=8.2]

Reference: OpenCSV Documentation, CsvTOBean Documentation, MappingStrategy



Similar Reads

Difference between Javabeans and Enterprise Javabeans
Notejava.beans: This package has been deprecated in Java 9 and later versions, in favor of using annotations and other modern ways of creating beans. Using it in production code is not recomended.JavaBeans: JavaBeans are recyclable software components for Java which by using a builder tool can be manipulated visually in line to a specific conventio
2 min read
Mapping Java Beans to CSV Using OpenCSV
The need to convert Java Beans(Objects) to CSV file arises very commonly and there are many ways to write Bean into CSV file but one of the best ways to map java bean to CSV is by using OpenCSV Library. In OpenCSV there is a class name StatefulBeanToCsvBuilder which helps to convert Java Beans to CSV. The first task is to add the OpenCSV library in
4 min read
Reading a CSV file in Java using OpenCSV
A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in column by column, and split it by a separator (e.g normally it is a comma “, ”). OpenCSV is a CSV parser library for Java. OpenCSV supports all the basic CSV-type operations you are want to do. Java 7 is currently the minimum supported version for OpenCSV. Java lang
7 min read
Writing a CSV file in Java using OpenCSV
A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in a column by column, and split it by a separator (e.g normally it is a comma “, ”). OpenCSV is a CSV parser library for Java. OpenCSV supports all the basic CSV-type operations you are want to do. Java 7 is currently the minimum supported version for OpenCSV. Java la
5 min read
CSV File Format | .csv Extension
What are CSV Files?The full form of CSV is Comma-separated values. Comma-separated value is a simple yet powerful file format to store and exchange data. Values are separated using commas in this plain text file format. CSV files are often used to store data in a tabular format, such as spreadsheets or databases. These files are easy to create and
3 min read
Hibernate Mapping Set using XML
In Hibernate, if we want to map one table to another with the help of a set then we use Set mapping. Set mapping can be performed if the model class or persistent class contains a set as its element. To perform set mapping, we can use a set in the mapping file. let's see how we can configure the XML mapping file for the mapping set in hibernate. Pr
5 min read
Hibernate - Bag Mapping
For a multi-national company, usually, selections are happened based on technical questions/aptitude questions. If we refer to a question, each will have a set of a minimum of 4 options i.e each question will have N solutions. So we can represent that by means of "HAS A" relationship i.e. 1 question has 4 solutions. Via Bag Mapping, in Hibernate, w
4 min read
What is Ambiguous Mapping in Spring?
Spring is a loosely coupled framework of java meaning all the objects are not dependent on each other and can be easily managed &amp; modified. Basic architecture in every spring project involves the use of controllers or REST Controllers, any build tool like maven, gradle, or groove, an RDBMS, Service layers, etc. Someone just starting into the sp
5 min read
How to Implement One to Many Mapping in Spring Boot?
Spring Boot is built on the top of the spring and contains all the features of spring. Spring also provides JPA and hibernate to increase the data manipulation efficiency between the spring application and the database. In very simple terms we can say JPA (Java persistence API) is like an interface and the hibernate is the implementation of the met
3 min read
Hibernate - One-to-One Mapping
Prerequisite: Basic knowledge of hibernate framework, Knowledge about databases, Java Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to
15 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg