Welcome to my blog, hope you enjoy reading
RSS

Friday 18 January 2013

How To Export Data To CSV File – Java


How To Export Data To CSV File – Java


CSV is stand for Comma-separated values, CSV is a delimited data format that has fields/columns separated by the comma character and records/rows separated by newlines.
Please take a look at a CSV sample,


Display Name,   Age, Hand Phone
Micheal , 30, 0123456789
Bill, 25, 0129876543
Actually CSV is just like a text file with a certain delimited like comma “,” or semi-comma “;” or any other delimited character you want. Here i will show how to use java to export data or writing data into a CSV file.
This sample is very simple and straight froward, it just use java FileWriter object to create a normal text file (CSV file).
package com.mkyong.test;
 
import java.io.FileWriter;
import java.io.IOException;
 
public class GenerateCsv
{
   public static void main(String [] args)
   {
    generateCsvFile("c:\\test.csv"); 
   }
 
   private static void generateCsvFile(String sFileName)
   {
 try
 {
     FileWriter writer = new FileWriter(sFileName);
 
     writer.append("DisplayName");
     writer.append(',');
     writer.append("Age");
     writer.append('\n');
 
     writer.append("aaa");
     writer.append(',');
     writer.append("26");
            writer.append('\n');
 
     writer.append("bbb");
     writer.append(',');
     writer.append("29");
     writer.append('\n');
 
     //generate whatever data you want
 
     writer.flush();
     writer.close();
 }
 catch(IOException e)
 {
      e.printStackTrace();
 } 
    }
}
Simple right? Writing or export data to a CSV file is exactly same with writing data into a normal text file. This is simple, we do not need any third party library to do it.

0 comments: