tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 CSV > OPEN CSV > Bean to CSV

Bean to CSV 

opencsv is a free and open source library for reading and writing CSV files in Java. We need to have opencsv-2.3.jar or later versions in classpath. The following example shows generating a CSV from java beans using opencsv.

File Name  :  
com/bethecoder/tutorials/open_csv/tests/Bean2CSV.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.open_csv.tests;

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

import au.com.bytecode.opencsv.CSVWriter;

import com.bethecoder.tutorials.open_csv.common.Student;

public class Bean2CSV {

  /**
   @param args
   @throws IOException 
   */
  public static void main(String[] argsthrows IOException {

    Student stud = new Student("Sriram"2"Chess");
    Student stud2 = new Student("Sudhakar"29"Painting");
    List<Student> students = Arrays.asList(stud, stud2);
    
    StringWriter sw = new StringWriter();
    CSVWriter writer = new CSVWriter(sw);
    
    //Write header
    String [] header = "name" "age""hobby" };
    writer.writeNext(header);
    
    //Write data
    String [] data;
    for (Student s : students) {
      data = new String [] { s.getName(), String.valueOf(s.getAge()) , s.getHobby() };
      writer.writeNext(data);
    }
    writer.close();

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

File Name  :  
com/bethecoder/tutorials/open_csv/common/Student.java 
   
package com.bethecoder.tutorials.open_csv.common;

public class Student {

  private String name;
  private int age;
  private String hobby;
  
  public Student() {
  }

  public Student(String name, int age, String hobby) {
    super();
    this.name = name;
    this.age = age;
    this.hobby = hobby;
  }
  
  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 getHobby() {
    return hobby;
  }
  public void setHobby(String hobby) {
    this.hobby = hobby;
  }
  
  public String toString() {
    return "Student[name = " + name + ", age = " + age + ", hobby = " + hobby + "]";
  }
}
   

It gives the following output,
Generated CSV : 

"name","age","hobby"
"Sriram","2","Chess"
"Sudhakar","29","Painting"



 
  


  
bl  br