How to Export Data to CSV file in JAVA

By | April 8, 2018

In this java tutorial and example you can learn “How to Export Data to CSV file in JAVA“. 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). Export data to CSV with Java programming language is very easy.

Note
Writing a CSV file is just like writing a normal text file, just beware of the “double-quotes” issue that mentions in 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. How to Export Data to CSV file in JAVA

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)

package com.cimblo.csvwritter;

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 values) throws IOException {
        writeLine(w, values, DEFAULT_SEPARATOR, ' ');
    }

    public static void writeLine(Writer w, List 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 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());


    }
}

Example to show the CSVUtils usage.

package com.cimblo.csvwritter;

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

public class Main {

    public static void main(String[] args) {
        System.out.println("For this example i'm using windows 10 for my Operating system");
        System.out.println("And for file output directory on local disk D");
        try {
            String csvFile = "D:\\cimblo.csv";
            FileWriter writer = new FileWriter(csvFile);

            CSVUtils.writeLine(writer, Arrays.asList("Tiket", "Traveloka", "Tokopedia", "Bukalapak", "Gojek"));

            //custom separator + quote
            CSVUtils.writeLine(writer, Arrays.asList("Blibli", "AlfaCart,WhatsApp", "UangTeman,Path"), ',', '"');

            //custom separator + quote
            CSVUtils.writeLine(writer, Arrays.asList("Elevenia", "Grab", "Uber,Line"), '|', '\'');

            //double-quotes
            CSVUtils.writeLine(writer, Arrays.asList("Instagram", "Google", "Chrome\"Firefox"));

            writer.flush();
            writer.close();
        } catch (Exception ignored) {}
    }
}

Output:

Tiket,Traveloka,Tokopedia,Bukalapak,Gojek
Blibli,"AlfaCart,WhatsApp","UangTeman,Path"
'Elevenia'|'Grab'|'Uber,Line'
Instagram,Google,Chrome""Firefox

2. Examples Write CSV in JAVA

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

A Developer class.

Developer.java
package com.cimblo.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;
    }

    //...
}

Example.

CVSUtilExample.java
package com.cimblo.utils;

import com.cimblo.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 = "D:\\cimblo.csv";
        FileWriter writer = new FileWriter(csvFile);

        List<Developer> developers = Arrays.asList(
                new Developer("cimblo", 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

Name,Salary,Age
tiket,120500,32
zilap,150099,5
ultraman,99999,99
Note
If you are still not comfortable to implement yourself, try this third party CSV library like OpenCSV.

Done.

References

  1. Ostermiller Java Utilities – Comma Separated Values (CSV)
  2. RFC4180 – Format for Comma-Separated Values (CSV)
  3. OpenCSV
  4. Wikipedia – Comma-Separated Values (CSV)

One thought on “How to Export Data to CSV file in JAVA

  1. Pingback: How to Read CSV file in JAVA ~ Cimblo.com

Leave a Reply

Your email address will not be published. Required fields are marked *