Searching...
Monday, 9 June 2014

OpenCSV creating csv records Example

11:36

Example

package com.vinod.opencsv;

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

import au.com.bytecode.opencsv.CSVWriter;

public class OpenCSVExample {
private static final char DELIMITER = ',';

/**
    *@param args
    */
public static void main(String[] args) {
StringWriter writer = new StringWriter();
CSVWriter csvWriter = null;

// Creating student objects
Student st1 = new Student("1", "vinod");
Student st2 = new Student("2", "raghav");
Student st3 = new Student("3", "shariff");

// Creating student object list
List studentList = new ArrayList();
studentList.add(st1);
studentList.add(st2);
studentList.add(st3);

try {

// Creating csvWriter object
csvWriter = new CSVWriter(writer, DELIMITER, 
CSVWriter.DEFAULT_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER, "\n");

List records = new ArrayList(10);

// Iterating student list and put it into new String array List
for (Student stud : studentList) {
List record = Arrays.asList(stud.getId(), stud.getName());

String recordArray[] = new String[record.size()];
record.toArray(recordArray);
records.add(recordArray);
}

// Writing string arrayList in to Stringwriter

csvWriter.writeAll(records);

// Spring String writer as csv records
System.out.println("CSV Details");
System.out.println(writer.toString());

} catch (Exception e) {
e.printStackTrace();
}

}
}

class Student {
private String id;
private String name;

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

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}
Output
CSV Details
"1","vinod"
"2","raghav"
"3","shariff"

0 comments: