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

Bean to CSV 

Super CSV is a free library for reading and writing CSV files in Java. We need to have SuperCSV-1.52.jar, spiffy-0.05.jar or later versions in classpath. The following example shows generating a CSV from java beans using Super CSV.

File Name  :  
com/bethecoder/tutorials/super_csv/tests/Bean2CSV.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.super_csv.tests;

import java.io.IOException;
import java.io.StringWriter;

import org.supercsv.io.CsvBeanWriter;
import org.supercsv.prefs.CsvPreference;

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

public class Bean2CSV {

  /**
   @param args
   @throws IOException 
   */
  public static void main(String[] argsthrows IOException {
    
    StringWriter sw = new StringWriter();
    CsvBeanWriter writer = new CsvBeanWriter(sw, CsvPreference.STANDARD_PREFERENCE);
    
    Student student = new Student("Sriram"2"Chess");
    Student student2 = new Student("Sudhakar"29"Painting");
    Student student3 = new Student("Charan"18"Reading books");
    
    String [] headers = "name""age""hobby" };
    
    writer.writeHeader(headers);
    writer.write(student, headers);
    writer.write(student2, headers);
    writer.write(student3, headers);
    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
Charan,18,Reading books


                    Print

   



Books Recommendation

 
 
bl  br