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

Mapping Java Beans to CSV Using OpenCSV

Last Updated : 09 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

  1. The first task is to add the OpenCSV library into the Project.

    • 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 JavaBeans to CSV
    Below is the step-by-step procedure to map Java Beans to CSV.

    1. Create Writer instance for writing data to the CSV file.

      Writer writer = Files.newBufferedWriter(Paths.get(file_location));
    2. Create a List of objects which are needed to be written into the CSV file.
    3. 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.
      
    4. 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();
      
    5. 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:

  1. Employee.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 + "]";
        }
    }

    
    

  2. BeanToCSV.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

Mapping CSV to JavaBeans Using OpenCSV
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 stra
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
Enterprise Java Beans (EJB)
Note java.beans: This package has been deprecated in Java 9 and later versions, in favor of using annotations and other modern ways of creating beans. Enterprise Java Beans (EJB) is one of the several Java APIs for standard manufacture of enterprise software. EJB is a server-side software element that summarizes business logic of an application. En
4 min read
Distributed Objects in EJB(Enterprise Java Beans) - Explicit vs Implicit Middleware
A distributed object is an object that is callable from a remote system. An in-process client, an out-process client, or an elsewhere located client (on a network) can call it. The following figure shows how a client can call a distributed object. Stub is a client-side proxy object. It masks the network communications from the client. Using the soc
5 min read
Implementing Message Queuing Technique in Netbeans Through Enterprise Java Beans
A Message Queues, allow one or more processes to write a message to be read by other processes. A message queue is implemented as a linked list of messages and is stored within the Kernel. Each message queue is identified by a message queue identifier. The Kernel keeps track of all the message queues created in a system. Procedure steps for Impleme
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
SQL Mapping with Java
SQL Mapping is an easier technique in which a normal user imagined columns(normally we say as metadata) are stored in the form of different tables. Each and every table information can be joined with other tables by means of special relationships like a Foreign key in a database. In each and every table, we will have Primary Key or Unique key to un
6 min read
Mapping a Dynamic JSON Object Field in Jackson with Java
All REST API services are providing the resultant output either as XML or JSON pattern only as both are portable in nature and among that JSON is more popular. We can expect unknown properties in a JSON object. There are different ways available to map dynamic JSON objects into Java classes. They are obviously required in many scenarios. Let us cov
5 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
Article Tags :
Practice Tags :
three90RightbarBannerImg