Site icon Narayana Tutorial

CSV File Writing By String Array and List

CSV File Writing By ResultSet

CSV File Writing By ResultSet

CSV File Writing By String Array and List

In the post I am going to explaining CSV File Writing By String Array and List by using opencsv jar file. You can see what is CSV file?. Find the below example and see how to create csv file by using String Array and List.

Before going to write java program we need to download opencsv jar file and assign to build path.

OpenCsvWriterByList.java

package com.narayanatutorial.opencsv;

import au.com.bytecode.opencsv.CSVWriter;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;


public class OpenCsvWriterByList {

    public static void main(String args[]) {
                String csvFilename = "D:/narayanatutorial/SampleFiles/OpenCSVWriteByList.csv";
        try {
            CSVWriter writer = new CSVWriter(new FileWriter(csvFilename));
            List<String[]> csvData = new ArrayList<String[]>();
            String[] profile = "Narayana,Ragi,30".split(",");
            String[] header="FIRSTNAME,LASTNAME,AGE".split(",");
            csvData.add(header);
            csvData.add(profile);
            
            writer.writeAll(csvData);
            writer.close();
            System.out.println("CSV file created succesfully.");
        } catch (Exception e) {
            System.out.println("exception :" + e.getMessage());
        }

    }
}

Output

CSV file created succesfully.

Open the generated csv file in the word excel and find the following output.

FIRSTNAME LASTNAME AGE
Narayana Ragi 30

Open the generated csv file in the notepad and find the following output.

"FIRSTNAME","LASTNAME","AGE"
"Narayana","Ragi","30"

you can find the above sample program in the github. If you have git account you can download from github and other sample programs also available and find the below github link to download. We used Netbeans IDE to develop sample programs. So you can directly import into Netbeans if you are having Netbeans else create sample project in your IDE and replace src folder.

Git link

I hope you understand CSV File Writing using String Array and List by using opencsv jar file.