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;   Â}   Â@Override   ÂpublicString 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 csv       ÂfinalString 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 =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 order           ÂColumnPositionMappingStrategy 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 object           ÂStatefulBeanToCsvBuilder<Employee> builder=                       ÂnewStatefulBeanToCsvBuilder(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
