Mapping Java Bean to CSV Using OpenCSV Library

When we write data from Java Object to a CSV file, we sometimes need to map the Java object properties directly to a CSV file.

The OpenCSV library provides the method to help us in such mapping and make the mapping process easy as mentioned below.

  • First, create a List of records of the Java Object and add data to it, and define columns and their order.
  • Next, create ColumnPositionMappingStrategy object and set the values for setType() and setColumnMapping() methods.
  • Next, create StatefulBeanToCsvBuilder object and define the writer using the above mapping strategy.
  • Finally, call the write() method to write the data from the list into a CSV file.

Sample Data

Let's assume the below data in the CSV file, with the default separator.

ID,Name,Class,Marks
1,Arun,10,520
2,Sravan,10,630
3,Kiran,10,580

And, the corresponding Java Class looks as below.

public class Student {
	private String id;
	private String name;
	private String standard;
	private String marks;
}

1. Generate Data & Columns

We have to build the mapping as shown below.

// Creating data
List<Student> list = new ArrayList<Student>();
list.add(new Student("1", "Arun", "10", "520"));
list.add(new Student("2", "Sravan", "10", "630"));
list.add(new Student("3", "Kiran", "10", "580"));

// Defining CSV file columns and their order
String[] columns = new String[] { "ID", "Name", "Class", "Marks" };

2. Define Mapping Strategy

Define the column position mapping strategy as shown below, which maps the Object properties to CSV header columns.

ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();
mappingStrategy.setType(Student.class);
mappingStrategy.setColumnMapping(columns);

3. Define Writer & Write Data from Object to CSV File

Define the CSVReader and CsvToBean objects as shown below.

// Creating StatefulBeanToCsv object
StatefulBeanToCsvBuilder<Student> builder = new StatefulBeanToCsvBuilder(writer);
StatefulBeanToCsv beanWriter = builder.withMappingStrategy(mappingStrategy).build();

// Write list to StatefulBeanToCsv object
beanWriter.write(list);

Complete Implementation

Here is the complete implementation.

public class CsvToBeanConversion {
    public static void main(String[] args) {
        try {
            // Creating data
            List<Student> list = new ArrayList<Student>();            
            list.add(new Student("1", "Arun", "10", "520"));
            list.add(new Student("2", "Sravan", "10", "630"));
            list.add(new Student("3", "Kiran", "10", "580"));
            
            // Defining columns and their order
            String[] columns = new String[] { "Name", "Age", "Company", "Salary" };
  
            // Define mapping strategy to arrange column names in order
            ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();
            mappingStrategy.setType(Student.class);            
            mappingStrategy.setColumnMapping(columns);
            
            // Creating writer class to generate CSV file
            FileWriter writer = new FileWriter("sample.csv");
  
            // Creating StatefulBeanToCsv object
            StatefulBeanToCsvBuilder<Student> builder = new StatefulBeanToCsvBuilder(writer);
            StatefulBeanToCsv beanWriter = builder.withMappingStrategy(mappingStrategy).build();
  
            // Write list data to StatefulBeanToCsv object
            beanWriter.write(list);
  
            // closing the writer object
            writer.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Conclusion

Now, we know how to write data from Java Object to CSV file by mapping object properties with CSV file headers.

Related Links

  • Java - Writing data to a CSV file
  • Java - Reading data from a CSV file
  • Java - Mapping data from a CSV file to Java beans
  • Java - Mapping data from Java beans to a CSV file