Mapping Java Beans to CSV Using OpenCSV
Last Updated :
09 Dec, 2021
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 into the Project.
-
Mapping JavaBeans to CSV
Below is the step-by-step procedure to map Java Beans to CSV.
-
Create Writer instance for writing data to the CSV file.
Writer writer = Files.newBufferedWriter(Paths.get(file_location));
- Create a List of objects which are needed to be written into the CSV file.
- Using ColumnPositionMappingStrategy map the columns of Created objects, to Column of csv.
This is an optional step. If ColumnPositionMappingStrategy is not used, then object will be written to csv with column name same as attribute name of object.
ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();
mappingStrategy.setType(Employee.class);
where Employee is the object to be mapped with CSV.
-
Create object of StatefulBeanToCsv class by calling build method of StatefulBeanToCsvBuilder class after the creation of StatefulBeanToCsvBuilder, with writer object as parameter. According to the requirement the user can also provide:
- ColumnPositionMappingStrategy with the help of withMappingStrategy function of StatefulBeanToCsvBuilder object.
- Separator of generated csv file with the help of withSeparator function of StatefulBeanToCsvBuilder object.
- withQuotechar of generated csv file with the help of withQuotechar function of StatefulBeanToCsvBuilder object.
StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)
.withMappingStrategy(mappingStrategy)
. withSeparator('#')
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.build();
-
After creating object of StatefulBeanToCsv class you can add list of object or object to csv file with the help of write method of StatefulBeanToCsv object.
beanToCsv.write(Employeelist);
Example: In this example, we are going to create the list of Employee Object which has attributes like Name, Age, Company, Salary. Then we will generate a CSV file Employees.csv which contains Employee objects.
Codes:
-
Employee.java
Java
public class Employee {
public String Name, Age, Company, Salary;
public Employee(String name, String age,
String company, String salary)
{
super();
Name = name;
Age = age;
Company = company;
Salary = salary;
}
@Override
public String toString()
{
return "Employee [Name=" + Name + ",
Age=" + Age + ", Company=" + Company + ",
Salary=" + Salary + "]";
}
}
-
BeanToCSV.java
Java
import java.io.FileWriter;
import java.io.Writer;
import java.nio.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
public class BeanToCSV {
public static void main(String[] args)
{
// name of generated csv
final String CSV_LOCATION = "Employees.csv ";
try {
// Creating writer class to generate
// csv file
FileWriter writer = new
FileWriter(CSV_LOCATION);
// create a list of employee
List<Employee> EmployeeList = new
ArrayList<Employee>();
Employee emp1 = new Employee
("Mahafuj", "24", "HTc", "75000");
Employee emp2 = new Employee
("Aman", "24", "microsoft", "79000");
Employee emp3 = new Employee
("Suvradip", "26", "tcs", "39000");
Employee emp4 = new Employee
("Riya", "22", "NgGear", "15000");
Employee emp5 = new Employee
("Prakash", "29", "Sath", "51000");
EmployeeList.add(emp1);
EmployeeList.add(emp2);
EmployeeList.add(emp3);
EmployeeList.add(emp4);
EmployeeList.add(emp5);
// Create Mapping Strategy to arrange the
// column name in order
ColumnPositionMappingStrategy mappingStrategy=
new ColumnPositionMappingStrategy();
mappingStrategy.setType(Employee.class);
// Arrange column name as provided in below array.
String[] columns = new String[]
{ "Name", "Age", "Company", "Salary" };
mappingStrategy.setColumnMapping(columns);
// Creating StatefulBeanToCsv object
StatefulBeanToCsvBuilder<Employee> builder=
new StatefulBeanToCsvBuilder(writer);
StatefulBeanToCsv beanWriter =
builder.withMappingStrategy(mappingStrategy).build();
// Write list to StatefulBeanToCsv object
beanWriter.write(EmployeeList);
// closing the writer object
writer.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
EmployeeData.csv
CSV file contains:-----
"Mahafuj", "24", "HTc", "75000"
"Aman", "24", "microsoft", "79000"
"Suvradip", "26", "tcs", "39000"
"Riya", "22", "NgGear", "15000"
"Prakash", "29", "Sath", "51000"
Reference: BeanToCsv Official Documentation
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read