How to export data to CSV file – Java

csv-writing

A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in column by column, and split it by separators (commas).

Note
Writing a CSV file is just like writing a normal text file, just beware of the “double-quotes” issue that mentions in my previous CSV parsing example.

In this tutorial, we will show you a simple CVSUtils class to write data or objects into a CVS file easily.

1. CSV Writing Example

1.1 Review the following CVSUtils class, it supports custom separator, custom enclose quote (default is empty), escaped the double-quotes with another double quote (RFC4180)

CSVUtils.java

package com.mkyong.utils;

import java.io.IOException;
import java.io.Writer;
import java.util.List;

public class CSVUtils {

    private static final char DEFAULT_SEPARATOR = ',';
    
    public static void writeLine(Writer w, List<String> values) throws IOException {
        writeLine(w, values, DEFAULT_SEPARATOR, ' ');
    }

    public static void writeLine(Writer w, List<String> values, char separators) throws IOException {
        writeLine(w, values, separators, ' ');
    }

    //https://tools.ietf.org/html/rfc4180
    private static String followCVSformat(String value) {

        String result = value;
        if (result.contains("\"")) {
            result = result.replace("\"", "\"\"");
        }
        return result;

    }

    public static void writeLine(Writer w, List<String> values, char separators, char customQuote) throws IOException {

        boolean first = true;

        //default customQuote is empty

        if (separators == ' ') {
            separators = DEFAULT_SEPARATOR;
        }

        StringBuilder sb = new StringBuilder();
        for (String value : values) {
            if (!first) {
                sb.append(separators);
            }
            if (customQuote == ' ') {
                sb.append(followCVSformat(value));
            } else {
                sb.append(customQuote).append(followCVSformat(value)).append(customQuote);
            }

            first = false;
        }
        sb.append("\n");
        w.append(sb.toString());


    }

}

1.2 Example to show the CSVUtils usage.

CSVUtils.java

package com.mkyong.utils;

import java.io.FileWriter;
import java.util.Arrays;

public class CVSUtilExample {

    public static void main(String[] args) throws Exception {

        String csvFile = "/Users/mkyong/csv/abc.csv";
        FileWriter writer = new FileWriter(csvFile);

        CSVUtils.writeLine(writer, Arrays.asList("a", "b", "c", "d"));

        //custom separator + quote
        CSVUtils.writeLine(writer, Arrays.asList("aaa", "bb,b", "cc,c"), ',', '"');

        //custom separator + quote
        CSVUtils.writeLine(writer, Arrays.asList("aaa", "bbb", "cc,c"), '|', '\'');

        //double-quotes
        CSVUtils.writeLine(writer, Arrays.asList("aaa", "bbb", "cc\"c"));


        writer.flush();
        writer.close();

    }

}

Output

/Users/mkyong/csv/abc.csv
a,b,c,d
"aaa","bb,b","cc,c"
'aaa'|'bbb'|'cc,c'
aaa,bbb,cc""c

2. More Examples

Let review another example, it creates a List of objects, and write it to a CSV file.

2.1 A Developer class.

Developer.java

package com.mkyong.csv;

import java.math.BigDecimal;

public class Developer {

    private String name;
    private BigDecimal salary;
    private int age;

    public Developer(String name, BigDecimal salary, int age) {
        this.name = name;
        this.salary = salary;
        this.age = age;
    }

    //...
}

2.2 Example.

CVSUtilExample.java

package com.mkyong.utils;

import com.mkyong.java8.Developer;

import java.io.FileWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CVSUtilExample {

    public static void main(String[] args) throws Exception {

        String csvFile = "/Users/mkyong/csv/developer.csv";
        FileWriter writer = new FileWriter(csvFile);

        List<Developer> developers = Arrays.asList(
                new Developer("mkyong", new BigDecimal(120500), 32),
                new Developer("zilap", new BigDecimal(150099), 5),
                new Developer("ultraman", new BigDecimal(99999), 99)
        );

        //for header
        CSVUtils.writeLine(writer, Arrays.asList("Name", "Salary", "Age"));
		
        for (Developer d : developers) {

            List<String> list = new ArrayList<>();
            list.add(d.getName());
            list.add(d.getSalary().toString());
            list.add(String.valueOf(d.getAge()));

            CSVUtils.writeLine(writer, list);

			//try custom separator and quote. 
			//CSVUtils.writeLine(writer, list, '|', '\"');
        }

        writer.flush();
        writer.close();

    }

}

Output

/Users/mkyong/csv/developer.csv
Name,Salary,Age
mkyong,120500,32
zilap,150099,5
ultraman,99999,99
Note
If you are still not comfortable to implement yourself, try this third party CSV library – OpenCSV.

Done.

References

  1. Ostermiller Java Utilities – Comma Separated Values (CSV)
  2. RFC4180 – Format for Comma-Separated Values (CSV)
  3. OpenCSV website
  4. How to parse a CSV file in Java
  5. Wikipedia – Comma-Separated Values (CSV)

About the Author

author image
mkyong
Founder of Mkyong.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

Leave a Reply

avatar
newest oldest most voted
Nuno
Guest
Nuno

Thank you for nice, ready to use example. Here is the JUnit version of your example:

package matrixStudio;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Arrays;

import org.junit.Test;

public class CSVUtilsTest {
// Unit tests for CSVUtils in https://www.mkyong.com/java/how-to-export-data-to-csv-file-java/
@Test
public void test_std() throws IOException {
Writer writer = new StringWriter();
CSVUtils.writeLine(writer, Arrays.asList(“a”, “b”, “c”, “d”));

String s=writer.toString();
System.out.println(“.”+s+”.”);
assert(s.equals(“a,b,c,dn”) );
}

public void test_quoted() throws IOException {
Writer writer = new StringWriter();
CSVUtils.writeLine(writer, Arrays.asList(“aaa”, “bb,b”, “cc,c”), ‘,’, ‘”‘);

assert(writer.toString().equals(“”aaa”,”bb,b”,”cc,c”n”) );
}

public void test_artistic() throws IOException {

Writer writer = new StringWriter();
CSVUtils.writeLine(writer, Arrays.asList(“aaa”, “bbb”, “cc,c”), ‘|’, ”’);

assert(writer.toString().equals(“‘aaa’|’bbb’|’cc,c'”) );
}

public void test_double() throws IOException {

Writer writer = new StringWriter();
CSVUtils.writeLine(writer, Arrays.asList(“aaa”, “bbb”, “cc”c”));

assert(writer.toString().equals(“”aaa”, “bbb”, “cc\”c””) );
}

}

Elijah
Guest
Elijah

The above seems like a fine solution for small data sets, but what would be a better way to approach writing out MILLIONS of lines of data?
I feel the above would result in Out of Memory exceptions if trying to load into any list or objects.

abc
Guest
abc

it is writing all in the same line in abc.csv file… not using new line .. plzzz help its urgent

abdulwahe
Guest
abdulwahe

In my case, it is also writing all in one line. Why is line separator not working? are we missing anything?

Hinotori
Guest
Hinotori

great!

Brutus
Guest
Brutus

This is some blatant spam. A much better way of doing this is to use the Apache Commons CSV library.

mkyong
Guest
mkyong

Article is updated with more features, for third party library, imho, prefer OpenCSV, easy to use.

Brutus
Guest
Brutus

Typo at the top, it isn’t CVS. But, much better than before!

Gabi
Guest
Gabi

this article is spam, it just writes text, no character escaping, no nothing

mkyong
Guest
mkyong

Article is updated to support double quotes escaping.

Robert
Guest
Robert

Hello mykong. Before your update you had a version with a method called “generateCsvFile(String sFileName). It inspired me for a work at university, but now I have the problem that I can’t quote it anymore… is there a possibility to get a link to this older version?

abc
Guest
abc

It is writing all in the same line in abc.csv file… not using new line .. plzzz help its urgent

abdulwahe
Guest
abdulwahe

I have fixed the issue by placing this line of code in my main method. By this it has started printing each record in a next line.

writer.write(System.getProperty(“line.separator”));

mkrowsft
Guest
mkrowsft

So many spam post, should do something about it affects quality of read, great post though..

sophie johnson
Guest
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;sdcsdc@sdf.com,dfwd@sd.com

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

thanks in advance! :)

Gaurav
Guest
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
Guest
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?

trackback
Build CSV dynamically in JSF 2 | BlogoSfera

[…] Basically what I want to do is this : http://www.mkyong.com/java/how-to-export-data-to-csv-file-java/ […]

Meriem
Guest
Meriem

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

cover letter for internship in engineering
Guest
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_

mittpaulforusall.com
Guest
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… Read more »
trackback
The Only Class You Need for CSV Files « Agile Software Craftsmanship

[…] How To Export Data To CSV File – Java – This implementation is simple, but it completely ignores the issues with commas and quotes in the data. Share this:TwitterFacebookLike this:LikeBe the first to like this.   Leave a comment […]

Monika
Guest
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
Guest
Anonymous

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

Artur
Guest
Artur

You can use SuperCSV

zyed
Guest
zyed

Hi mkyong,

I hava requirement export .ics format for my custom fields

Any help…

Thanks

Ravi Deshmukh
Guest
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
Guest
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

Rajkumari
Guest
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,

Michael
Guest
Michael

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

rajavijayakanth
Guest
rajavijayakanth

how to insert .csv file values into mongodb?

Shaher
Guest
Shaher

hi

Martyn
Guest
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… Read more »
Shaher
Guest
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
Guest
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

SK
Guest
SK

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

pooja
Guest
pooja

Thanks. It was helpful.

tomi adewole
Guest
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

Ab
Guest
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
Guest
o?uz

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