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 CSV.
- 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.
- For maven project,include the OpenCSV maven dependency in pom.xml file.
- 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);
- Create Writer instance for writing data to the CSV file.
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
publicclassEmployee {publicString Name, Age, Company, Salary;publicEmployee(String name, String age,String company, String salary){super();Name = name;Age = age;Company = company;Salary = salary;}@OverridepublicString toString(){return"Employee [Name="+ Name + ",Age=" + Age + ", Company=" + Company + ",Salary=" + Salary + "]";}} - BeanToCSV.java
importjava.io.FileWriter;importjava.io.Writer;importjava.nio.*;importjava.nio.file.Files;importjava.nio.file.Paths;importjava.util.*;importcom.opencsv.bean.ColumnPositionMappingStrategy;importcom.opencsv.bean.StatefulBeanToCsv;importcom.opencsv.bean.StatefulBeanToCsvBuilder;publicclassBeanToCSV {publicstaticvoidmain(String[] args){// name of generated csvfinalString CSV_LOCATION ="Employees.csv ";try{// Creating writer class to generate// csv fileFileWriter writer =newFileWriter(CSV_LOCATION);// create a list of employeeList<Employee> EmployeeList =newArrayList<Employee>();Employee emp1 =newEmployee("Mahafuj","24","HTc","75000");Employee emp2 =newEmployee("Aman","24","microsoft","79000");Employee emp3 =newEmployee("Suvradip","26","tcs","39000");Employee emp4 =newEmployee("Riya","22","NgGear","15000");Employee emp5 =newEmployee("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 orderColumnPositionMappingStrategy mappingStrategy=newColumnPositionMappingStrategy();mappingStrategy.setType(Employee.class);// Arrange column name as provided in below array.String[] columns =newString[]{"Name","Age","Company","Salary"};mappingStrategy.setColumnMapping(columns);// Creating StatefulBeanToCsv objectStatefulBeanToCsvBuilder<Employee> builder=newStatefulBeanToCsvBuilder(writer);StatefulBeanToCsv beanWriter =builder.withMappingStrategy(mappingStrategy).build();// Write list to StatefulBeanToCsv objectbeanWriter.write(EmployeeList);// closing the writer objectwriter.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



