Java Export to CSV File Example
- Details
- Written by Nam Ha Minh
- Last Updated on 12 December 2023   |   Print Email
This tutorial shows you how to use Super CSV to write data from POJOs (Plain Old Java Objects) to a CSV file. Typically, we write values of fields of a POJO class to a row in the CSV file. The Super CSV library provides the CsvBeanWriter class which makes this process a breeze.
To use Super CSV, add super-csv-VERSION.jar file to the classpath or use the following Maven dependency:
<dependency> <groupId>net.sf.supercsv</groupId> <artifactId>super-csv</artifactId> <version>VERSION</version> </dependency>
Replace VERSION by the actual version number, i.e. 2.1.0 is the current version of Super CSV.
1. Writing POJO class
Suppose that we have the following POJO class (Book.java):
package net.codejava.supercsv; import java.util.Date; public class Book { private String isbn; private String title; private String author; private String publisher; private Date published; private double price; public Book() { // this empty constructor is required } public Book(String isbn, String title, String author, String publisher, Date published, double price) { this.isbn = isbn; this.title = title; this.author = author; this.publisher = publisher; this.published = published; this.price = price; } // getters and setters }
And we have a list of Books object:
List<Book> listBooks = new ArrayList<Book>(); listBooks.add(book1); listBooks.add(book2); ...
Now, we want to export this list of Books to a CSV file, with each row containing values of fields of each Book object. The values are separated by commas, and each field value corresponds to a column. For example:
0321356683,Effective Java,Joshua Bloch,Addision-Wesley,05/08/2008,38.0
2. Defining cell processors
Super CSV provides some built-in classes called cell processors that convert Java data types to Strings (when writing to CSV file) and vice-versa (when reading from CSV file). For example: the NotNull processor ensures that the column is not null; the FmtDate processor converts a Date to a String using a specified date format; the ParseDouble processor converts a Double to a String, etc.
For the above POJO class, we create the following array of processors:
CellProcessor[] processors = new CellProcessor[] { new NotNull(), // ISBN new NotNull(), // title new NotNull(), // author new NotNull(), // publisher new FmtDate("MM/dd/yyyy"), // published date new ParseDouble() // price };
Note that the order of processors must match the order of columns which we want to write to the CSV file.
3. Writing CSV file using CsvBeanWriter
The following code snippet gives you an idea of how to write data to a CSV file using the CsvBeanWriter class with the above cell processors:
ICsvBeanWriter beanWriter = new CsvBeanWriter(new FileWriter(csvFileName), CsvPreference.STANDARD_PREFERENCE); String[] header = {"isbn", "title", "author", "publisher", "published", "price"}; beanWriter.writeHeader(header); for (Book aBook : listBooks) { beanWriter.write(aBook, header, processors); }
First, this code writes a header row that contains column names. Then it iterates through the list of Books object and writes each object to a row in the CSV file. Note that the header array must contain values matching the names of the properties defined in the POJO class.
And here is code of a complete utility method:
static void writeCSVFile(String csvFileName, List<Book> listBooks) { ICsvBeanWriter beanWriter = null; CellProcessor[] processors = new CellProcessor[] { new NotNull(), // ISBN new NotNull(), // title new NotNull(), // author new NotNull(), // publisher new FmtDate("MM/dd/yyyy"), // published date new ParseDouble() // price }; try { beanWriter = new CsvBeanWriter(new FileWriter(csvFileName), CsvPreference.STANDARD_PREFERENCE); String[] header = {"isbn", "title", "author", "publisher", "published", "price"}; beanWriter.writeHeader(header); for (Book aBook : listBooks) { beanWriter.write(aBook, header, processors); } } catch (IOException ex) { System.err.println("Error writing the CSV file: " + ex); } finally { if (beanWriter != null) { try { beanWriter.close(); } catch (IOException ex) { System.err.println("Error closing the writer: " + ex); } } } }
4. Java Export to CSV Example program
The following code is for a simple test program with some dummy data:
package net.codejava.supercsv; import java.io.FileWriter; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.List; import org.supercsv.cellprocessor.FmtDate; import org.supercsv.cellprocessor.ParseDouble; import org.supercsv.cellprocessor.constraint.NotNull; import org.supercsv.cellprocessor.ift.CellProcessor; import org.supercsv.io.CsvBeanWriter; import org.supercsv.io.ICsvBeanWriter; import org.supercsv.prefs.CsvPreference; /** * This program demonstrates how to write fields of POJOs to a CSV file * using SuperCSV library. Each JavaBean's fields are written to a row * in the CSV file. * @author www.codejava.net * */ public class CsvBeanWriterExample { static void writeCSVFile(String csvFileName, List<Book> listBooks) { // same code as the above } public static void main(String[] args) throws ParseException { // creates some dummy data DateFormat dateFormater = new SimpleDateFormat("MM/dd/yyyy"); Book book1 = new Book("0321356683", "Effective Java", "Joshua Bloch", "Addision-Wesley", dateFormater.parse("05/08/2008"), 38.00); Book book2 = new Book("0321356683", "Head First Java", "Kathy Sierra & Bert Bates", "O'Reilly Media", dateFormater.parse("02/09/2005"), 30.00); Book book3 = new Book("0131872486", "Thinking in Java", "Bruce Eckel", "Prentice Hall", dateFormater.parse("02/26/06"), 45.00); Book book4 = new Book("0596527756", "", "Naftalin & Philip Wadler", "O'Reilly Media", dateFormater.parse("10/24/2006"), 27.00); List<Book> listBooks = Arrays.asList(book1, book2, book3, book4); String csvFileName = "Java_Books.csv"; writeCSVFile(csvFileName, listBooks); } }
The following text is content of the CSV file generated by the above program:
isbn,title,author,publisher,published,price 0321356683,Effective Java,Joshua Bloch,Addision-Wesley,05/08/2008,38.0 0321356683,Head First Java,Kathy Sierra & Bert Bates,O'Reilly Media,02/09/2005,30.0 0131872486,Thinking in Java,Bruce Eckel,Prentice Hall,02/26/0006,45.0 0596527756,,Naftalin & Philip Wadler,O'Reilly Media,10/24/2006,27.0
You can get the code example on GitHub or download the attachment below.
To read data from CSV file, read this tutorial: Java Read Data from CSV File Example
References:
Other Java Coding Tutorials:
- 10 Common Mistakes Every Beginner Java Programmer Makes
- 10 Java Core Best Practices Every Java Programmer Should Know
- How to become a good programmer? 13 tasks you should practice now
- How to calculate MD5 and SHA hash values in Java
- How to generate random numbers in Java
- Java File Encryption and Decryption Example
Comments
The CSV file gets saved in the same directory as the program.