CSV Write Using Java

Wednesday, July 29, 2009

CSV, comma separated values, files are commonly used to transport large amounts of tabular data between either companies or applications that are not directly connected. The files are easily editable using common spreadsheet applications like Microsoft Excel.

Fields are separated by commas.
Records are separated with system end of line characters, CRLF (ASCII 13 Dec or 0D Hex and ASCII 10 Dec or 0A Hex respectively) for Windows, LF for Unix, and CR for Mac.

For this application you need one jar file
That is : SuperCSV-1.52.jar


JExcelWriteExample.java


/**
* File Name : CSVWriteExample.java
* Created By : Nagaraju V
* Created Date : Aug 06, 2009
* Purpose : Writing Data to Excel in csv format.
*/
package com.raj.csv;

import java.io.FileWriter;
import java.util.HashMap;
import org.supercsv.io.*;
import org.supercsv.prefs.CsvPreference;
/**
* @author nagarajuv
*
*/
public class CSVWriteExample {

/**
* @param args
*/
public static void main(String[] args) throws Exception{

ICsvMapWriter writer = new CsvMapWriter(new FileWriter("person.csv"), CsvPreference.EXCEL_PREFERENCE);
try {
final String[] header = new String[] { "name", "city", "pin" };
// set up some data to write
final HashMap data1 = new HashMap();
data1.put(header[0], "Raj");
data1.put(header[1], "Vijayawada");
data1.put(header[2], 500026);
final HashMap data2 = new HashMap();
data2.put(header[0], "Suneel");
data2.put(header[1], "Tenali");
data2.put(header[2], 522202);

// the actual writing
writer.writeHeader(header);
writer.write(data1, header);
writer.write(data2, header);

System.out.println("Writing Completed...!");
} finally {
writer.close();
}
}
}

The following source code contains supercsv jar and code. All the best.
Image Hosted by ImageShack.us
Image Hosted by ImageShack.us

0 comments: