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

  • Pingback: Google()

  • sophie johnson

    i have a text file which has a “;” delimited text and the text in between contains the commas(,). is there any way to change the delimeter of a csv file?
    for example a line in my text file has something like,

    firstname;lastname;892342989,23436489;[email protected],[email protected]

    now i want to create a csv file that has text seperated by “;” in each column.

    thanks in advance! :)

  • Gaurav

    I have a query here..I am doing a project in which I need to convert any type of database into csv file..now the problem I m getting is that how can I know in advance what the table column names are and how can I dynamically change the field name of a csv..
    Any help is appreciated..thanx in advance :)

  • Dave Blick

    I don’t agree with you that frameworks aren’t needed Your example is indeed “simple”. For example, It would fail if the strings you are outputting had commas or quotes in them. A framework (like POI) would handle those issues without you even being aware of them.

    Admittedly, CSVs are fairly lightweight… and don’t have as many of these sorts of issues as other formats, but why re-invent the wheel?

  • Pingback: Build CSV dynamically in JSF 2 | BlogoSfera()

  • Meriem

    hi please i want to know How to export data from DBF file to CSV file

  • http://wiki.bohyne.net/index.php/U%C5%BEivatel:ArmandoGe cover letter for internship in engineering

    I needed to thank you for this fantastic read!! I absolutely loved every bit of it.
    I have you saved as a favorite to check out new stuff you post_

  • http://mittpaulforusall.com/blogs/user/AugustaBea mittpaulforusall.com

    If owning your own home is causing that you simply financial hardship
    but you’re unable to sell the property to get out from underneath the burden, there are options available that can help you avoid foreclosure. Choose derived from one of of these packages which will help you with the house advance payment, monthly amortization, or reduce your procurment cost. Many of the grants are set aside for no traditional students. Now download the grant forms as well as other package information. You have to be free of all these encumbrances to have a high possibility of receiving a mortgage grant which will help improve your life.

  • Pingback: The Only Class You Need for CSV Files « Agile Software Craftsmanship()

  • Monika

    The example of yours is converting hardcoded values to .csv file.
    In my case i dont know the schema of the table..all i know is the name of the table and wer it resides,So can u help me in finding the best possible way to get the csv file in the below format;
    tableName:ColName1,ColName2…ColName’n’
    colElement1,colElement2,…,colElement’n’
    .
    .
    .
    [Till the last row.]

    Please reply!!!

    • Anonymous

      Don’t You Think it’s Simple ?!.All you need is Jdbc to connect to any Database.

  • zyed

    Hi mkyong,

    I hava requirement export .ics format for my custom fields

    Any help…

    Thanks

  • http://www.thaifishing4u.com/smf/index.php?action=profile;u=194046 Ravi Deshmukh

    Do you have a spam issue on this website; I also am a blogger, and I was wondering your situation; many of us have developed some nice practices
    and we are looking to trade strategies with other folks,
    please shoot me an email if interested.

  • murali

    how I can I import all my data from the table in .sql format.I am having nearly 25000+ rows in my tabel,is there any way we can do it in hiberante like schema export..? if nt please provide me any solution irrespective of hiberante

  • http://www.railsboxtech.com/ Rajkumari

    Hello,

    Nice article it help to create csv file in both java and android.
    Can you please tell me that is it possible to send image also in csv file.
    If it is possible then please help me…

    Thanks In Advance,

  • http://best-endowment-policy.blogspot.com/ Michael

    This is a very good resource. Have been looking for how to do this all day. Thanks.

  • rajavijayakanth

    how to insert .csv file values into mongodb?

  • Shaher

    hi

    • Martyn

      I just wrote this class based on your example – lets you build up a grid of data, then write it out to file in one call:

      import java.io.FileWriter;
      import java.io.IOException;
      import java.util.Iterator;
      import java.util.Vector;

      public class ResultsGrid
      {
      public ResultsGrid(){
      newLine();
      }

      public void generateCSVFile(String sFileName)
      {
      try
      {
      FileWriter writer = new FileWriter(sFileName);

      Iterator<Vector> rowI = grid.iterator();

      while (rowI.hasNext()){
      Vector row = rowI.next();
      Iterator elI = row.iterator();
      while (elI.hasNext()){
      writer.append(elI.next());
      if (elI.hasNext()){
      writer.append(‘,’);
      }
      }
      writer.append(‘\n’);
      }

      writer.flush();
      writer.close();
      }
      catch(IOException e)
      {
      e.printStackTrace();
      }
      }

      public void newLine(){
      grid.add(new Vector());
      }

      public void addField(String data){
      String toAdd = “\”” + data + “\””;
      grid.lastElement().add(toAdd);
      }

      public void addField(int data){
      grid.lastElement().add(Integer.toString(data));
      }

      public void addField(double data){
      grid.lastElement().add(Double.toString(data));
      }

      public void addFields(double[] data){
      for (int i=0; i<data.length; ++i){
      addField(data[i]);
      }
      }

      public void addFields(int[] data){
      for (int i=0; i<data.length; ++i){
      addField(data[i]);
      }
      }

      Vector<Vector> grid = new Vector<Vector>();
      }

  • Shaher

    Thanks for sharing this helpful article,

    What is the character that are used to center the text inside the cell? Also, is there a character used to expand the cell to the size of the text?

    Thanks
    Shaher

  • Anon

    What if you are referencing a variable and need to write that into the CSV file, see my source code below:

    public static void main(String args[])
    	{
    		try 
    		{
    			FileWriter printer = new FileWriter("c:\\test2.csv");
     
    			Class c = Class.forName("java.lang.String");
    			Method m[] = c.getDeclaredMethods();
    			for (int i = 0; i < m.length; i++)
    			System.out.println(m[i].toString());
    			System.out.println("_____");
    			System.out.println("There are " + m.length + " method in TOTAL in this class");
     
    			printer.append("CLASSNAME");
    			printer.append(',');
    			printer.append("NUMBER OF METHODS");
    			printer.append('\n');
     
    			printer.append(); // NEED TO USE THE VARIABLE c here
    			printer.append(',');
    			printer.append(); // NEED TO USE THE VARIABLE m here
    			printer.append('\n');
     
    			printer.flush();
    			printer.close();
     
    		}
     
    		catch(Throwable e)
    		{
    			System.err.println(e);
    		}
     
    	}
    }

    Any reply will be very useful on this thank you!
    Anon x

    • http://www.mkyong.com mkyong

      CVS is nothing but a text file, make your variable output as text.

      Actually, don’t really know what you mean by use “variable c or m”, just get the c.getMethod.returnAsString() will do.

  • SK

    Thank you so much. This one is really simple and easy to understand.

  • pooja

    Thanks. It was helpful.

  • http://article-marketing-tools.blogspot.com tomi adewole

    Hello sir; is there a way to export a txt file right into a csv with a program? Can’t be done manually because list is too long. Thanks for the consideration

    • http://www.mkyong.com mkyong

      Just write a simple program like what mention in above article.

  • Ab

    The example of yours is converting hardcoded values to .csv file.
    In my case i dont know the schema of the table..all i know is the name of the table and wer it resides,So can u help me in finding the best possible way to get the csv file in the below format;
    tableName:ColName1,ColName2…ColName’n’
    colElement1,colElement2,…,colElement’n’
    .
    .
    .
    [Till the last row.]

    Please reply!!!

  • o?uz

    how does create new worksheet in csv by using Java????

  • Pingback: Help with a beginner's java assignment: Survey results - Page 2 - Java Programming Forums()

  • Jacques

    And if you have a double quote in one of your fields? This is fairly simple to deal with but it should be mentionned. Replace all double quotes in any field with two double quotes, and enclose the whole in double quotes. The safe thing to do is always write one’s fields out enclosed by double quotes.

  • http://www.yahoomail.com Deepa

    how can i generate csv file using junit api testing

    • http://www.mkyong.com mkyong

      Could you be more specified? In JUnit, just create a fucntion and generate the csv file, why not?

  • Prateek

    How can we embed an image in the CSV file??? Please help

    • http://www.mkyong.com mkyong

      er…may i know why you want to embed an image in CSV file?

  • Ronnie

    Hi mkyong….
    Srry it was simple…
    I did cast it to string and use it :)
    But however i could not append the time stamp(date + time) value. The timestamp value format is of YYYY:MM:DD HRS:MIN …..
    But when appending it is only giving HRS:MIN value i.e the time value but the date value is completely lost :(

    • mkyong

      would you mind to share your code here? or email me?

      • vigun

        Hi,
        I am exporting csv file with data like 10-02-10. while try to open using excel it is automatically formatting as 02/10/2010.Please help, how to stop auto formatting or any other code we have to use while export.

  • Ronnie

    What if i want to append double and integer values to the same files?
    file writer append doesnt support double or int values….

  • No name

    >>> Simple right? Writing / export data to CSV file is exactly same with writing data into a normal text file.

    Wrong. What if you have “,” in your, say, Display Name field?

    • mkyong

      hi no name,

      Ya, i agreed with you, my function above is quite simple and it is not enough to cover all CVS functionality. However what i want to bring out is, we can generate the CVS file by simple output it as text file.
      If we have a comma(,) , we need to use double quote (“) to enclose it.

      For example

      “No , name”, 23

      Thanks for bringing this to my attention, :)

      P.S Please refer to this link for CVS detail

      http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm