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.

More detail please check http://en.wikipedia.org/wiki/Comma-separated_values

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("MKYONG");
	    writer.append(',');
	    writer.append("26");
            writer.append('\n');
 
	    writer.append("YOUR NAME");
	    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.

Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments