Mapping CSV to JavaBeans Using OpenCSV
Last Updated :
05 Jan, 2023
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.
- 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.
- Mapping CSV to JavaBeans Mapping a CSV to JavaBeans is simple and easy process. Just follow these couple of steps:
- 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.
- Create HeaderColumnNameTranslateMappingStrategy object pass mapping hashmap to setColumnMapping method.
HeaderColumnNameTranslateMappingStrategy strategy =
new HeaderColumnNameTranslateMappingStrategy();
strategy.setType(JavaBeanObject.class);
strategy.setColumnMapping(mapping);
- Create the object of CSVReader and CsvToBean class
String csvFilename = "data.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
CsvToBean csv = new CsvToBean();
- 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:
- 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 + "]";
}
}
- 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
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 CS
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 th
7 min read
How to Load an Image using OpenCV in Android?
OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library which is used for image and video processing. In this article, we are going to build an application that shows the demonstration of how we can load images in OpenCV on Android. Mat Cl
4 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
5 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
5 min read
PostgreSQL CRUD Operations using Java
CRUD (Create, Read, Update, Delete) operations are the basic fundamentals and backbone of any SQL database system. CRUD is frequently used in database and database design cases. It simplifies security control by meeting a variety of access criteria. The CRUD acronym identifies all of the major funct
8 min read
Spring Boot Batch Processing Using Spring Data JPA to CSV File
The Spring Batch is a framework in the Spring Boot ecosystem It can provide a lot of functionalities for Batch processing. The Spring Batch framework simplifies the batch development of applications by providing reliable components and other patterns for common batch processing concerns. Mostly, bat
7 min read
How to Upload Multiple Files using Java Servlet?
Servlets are the server-side programs used to create dynamic web pages. They can be used to upload files on the server. This article shows two approaches for uploading multiple files on the server. index.jsp Set method: This is an attribute of <form> tag which is used to specify the http metho
3 min read
How to Plot a Graph in Android Using CSV File?
When we are dealing with large amounts of data sets and if we want to display the data graphically then it becomes sometimes tough to generate a graph using that data so in this article we are going to implement this in an easy manner and you can add any types of graph and charts like BarChart, PieC
5 min read
How to export HTML table to CSV using JavaScript ?
Comma Separated Values or CSV is a type of text file where each value is delimited by a comma. CSV files are very useful for the import and export of data to other software applications.Sometimes while developing web applications, you may come into a scenario where you need to download a CSV file co
6 min read