Download OpenCSV: http://sourceforge.net/projects/opencsv/files/latest/download

OpenCSV is a free and open source library for reading and writing CSV files in Java. We need to have latest opencsv jar in classpath. Following example shows generating a CSV from java beans using opencsv.

Bean2CSV.java

import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.List;

import au.com.bytecode.opencsv.CSVWriter;

public class Bean2CSV {

  public static void main(String[] args) throws IOException {

    Student stud1 = new Student("Mayur", 25);
    Student stud2 = new Student("Vishal", 26);
    List<Student> students = Arrays.asList(stud1, stud2);

    StringWriter sw = new StringWriter();
    CSVWriter writer = new CSVWriter(sw);

    //Write header
    String [] header = { "name", "age" };
    writer.writeNext(header);

    //Write data
    String [] data;
    for (Student s : students) {
      data = new String [] { s.getName(), String.valueOf(s.getAge()) };
      writer.writeNext(data);
    }
    writer.close();

    System.out.println("Generated CSV : \n");
    System.out.println(sw.toString());
  }
}

Student.java

public class Student {

  private String name;
  private int age;

  public Student() {
  }

  public Student(String name, int age) {
    super();
    this.name = name;
    this.age = age;
  }

  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }

  public String toString() {
    return "Student[name = " + name + ", age = " + age + "]";
  }
}

Output:

Generated CSV :
“name”,”age”
“Mayur”,”25″
“Vishal”,”26″