Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Mapping CSV to JavaBeans Using OpenCSV

  • Last Updated : 17 Jul, 2018

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.

    Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

    • For maven project, include the OpenCSV maven dependency in pom.xml file.




      <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.
  2. 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");
      

      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);
      
    3. Create the object of CSVReade and CsvToBean class
      String csvFilename = "data.csv";
      CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
      CsvToBean csv = new CsvToBean();
      
    4. 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




    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 + "]";
        }
    }
  2. csvtobean.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 castobaen 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




My Personal Notes arrow_drop_up
Recommended Articles
Page :