Sample code for 30+ languages & platforms
Java

Create CSV File

See more CSV Examples

Demonstrates how to create a new CSV file with some simple content.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Csv;

public class ChilkatExample {

    public static void main(String[] args) {
        // This sample code creates a new CSV file (sample.csv)
        // that contains this content:
        //
        // year,color,country,food
        // 2001,red,France,cheese
        // 2005,blue,"United States",hamburger

        Csv csv = new Csv();

        // Indicate that the 1st row
        // should be treated as column names:
        csv.setHasColumnNames(true);

        csv.setColumnName(0, "year");
        csv.setColumnName(1, "color");
        csv.setColumnName(2, "country");
        csv.setColumnName(3, "food");

        csv.setCell(0, 0, "2001");
        csv.setCell(0, 1, "red");
        csv.setCell(0, 2, "France");
        csv.setCell(0, 3, "cheese");

        csv.setCell(1, 0, "2005");
        csv.setCell(1, 1, "blue");
        csv.setCell(1, 2, "United States");
        csv.setCell(1, 3, "hamburger");

        // Write the CSV to a string and display:
        String csvDoc = csv.saveToString();
        System.out.println(csvDoc);

        // Save the CSV to a file:
        try {
            csv.saveFile("out.csv");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
        }
    }
}