Mapping CSV to JavaBeans using OpenCSV


CSV files are basically plain text files that stores data in columns separated a comma. OpenCSV is the library that parses these CSV files which are quite difficult to handle otherwise. It is a quite easy to use library that supports several features like reading and writing of CSV files with headers.

We will be discussing the mapping of CSV files to JavaBeans via OpenCSV in this article. Additionally. OpenCSV is a tool that aids in this process.

Mapping the CSV to JavaBeans

The OpenCSV library provides certain classes and mapping strategies to map the CSV files into Java Beans. One such class is CSVToBean which is used to map the CSV files to the JavaBeans. To parse these CSV files, CSVToBean class needs a mapping strategy that needs to be defined and passed to the CSVToBean class. One such popular mapping strategy is HeaderColumnNameTranslateMappingStrategy which maps the column ids to the java bean properties.

Syntax

The mapping of CSV files to beans is done in a series of steps. However, syntax for the creating the HashMap with a mapping between the column ids and beam properties is as follows −

HashMap map = new HashMap();
map.put("column_id", "bean_property");

At first, we have created a hashmap, and then mapped the column ids with the respective Java bean properties using the put() function of HashMap.

Algorithm

  • Step 1 − First add the OpenCSV to the Java project using the following dependencies.

For a maven project, add the following dependency to the java project −

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

For a gradle project, you need to add the following dependency −

compile group: 'com.opencsv', name: 'opencsv', version: '4.1'
  • Step 2 − Now, let us start the basic steps to map the csv files into Java Beans.

  • Step 3 − Create a HashMap with a mapping between the column id and the bean property.

  • Step 4 − Add all the column ids of the csv file corresponding to the bean property.

  • Step 5 − Create the object of the HeaderColumnNameTranslateMappingStrategy.

  • Step 6 − Now, pass the mapped hashmap to setColumnMapping() method.

  • Step 7 − Call the objects of the CSVToBean and CSVReader class.

  • Step 8 − Now, we will call the parsing method of CSVToBean class and pass the HeaderColumnNameTranslateMappingStrategy and CSVReader objects to it.

  • Step 9 − Print the details of the Bean object.

Approach

Now, let us map the contents of a Employee.csv file to JavaBeans using OpenCSV. The Employee.csv file contains the data like employee name , department, and salary.

The contents of the Employee.csv file are as follows −

Employee_Name, Department, Salary
Naman, Human Resource, 45000
Nikita, Sales, 35000
Rocky, IT, 50000
Raman, Human Resource, 42000

Now, let us first create the Employee class and then the main method which maps the content of this csv file to JavaBeans.

Example: Employee.java

public class Employee {
   private static final long serialVersionUID = 1L;
 
   public String emp_name, department, salary;
 
    public String getName() {
      return emp_name;
   }
 
   public void setName(String n) {
      emp_name  = n;
   }
 
   public String getSalary() {
      return salary;
   }
 
   public void setSalary(String s) {
      salary = s;
   }
 
   public String getDepartment() {
      return department;
   }
 
   public void setDepartment(String d) {
      d = department;
   }
   public String toString() {
      return "Employee [Name=" + emp_name + ", Department= " + department +",
         Salary = " + salary+ "]";
   }
}

Below is the program code for CsvToBean.java file.

Example

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) {
      Map<String, String> map = new HashMap<>();
      map.put("Employee_Name", "emp_name");
      map.put("Department", "department");
      map.put("Salary", "salary");
      HeaderColumnNameTranslateMappingStrategy<Employee> s =
         new HeaderColumnNameTranslateMappingStrategy<>();
      s.setType(Employee.class);
      s.setColumnMapping(map);
      CSVReader csvReader = null;
      try {
         csvReader = new CSVReader(new FileReader
         ("D:\CSVFiles\Employee.csv"));
      }
      catch (FileNotFoundException e) {
         e.printStackTrace();
      }
      CsvToBean csvToBean = new CsvToBean();
      List<Employee> l = csvToBean.parse(s, csvReader);
      for (Employee x : l) {
         System.out.println(x);
      }
   }
}

Output

Employee [Name=Naman, Department=Human Resource, Salary=45000]
Employee [Name=Nikita, Department=Sales, Salary=35000]
Employee [Name=Rocky, Department=IT, Salary=50000]
Employee [Name=Raman, Department=Human Resource, Salary=42000]

As you can see in the above program code, we have first created a hashmap for mapping the column ids with the corresponding bean property. After which we have implemented the HeaderColumnNameTranslateMappingStrategy strategy for the Employee class and passed it to the parse method of CsvToBean class for mapping the CSV to JavaBean using OpenCSV.

Conclusion

In this article, we have studied how to map the CSV files to JavaBeans using OpenCSV. The simple technique discussed for performing this action is using the CsvToBean class and a mapping strategy which is passed to the object of the CsvToBean class. We have discussed the steps and the program code for parsing an employee data in the csv format to JavaBeans using OpenCSV.

Updated on: 28-Jul-2023

832 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements