Site icon Narayana Tutorial

CSV File Writing By View Object and List

CSV File Writing By ResultSet

CSV File Writing By ResultSet

CSV File Writing By View Object and List

 

In the post I am going to explaining CSV File Writing By View Object 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 view object(VO) and list.

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

OpenCsvWriterByBeanList.java

package com.narayanatutorial.opencsv;

import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;

public class OpenCsvWriterByBeanList {

    public static void main(String args[]) {
                String csvFilename = "D:/narayanatutorial/SampleFiles/OpenCSVWriteByBeanList.csv";
                String Comma=",";
                String newLine="\n";
        try {
            FileWriter writer = new FileWriter(csvFilename);
            Profile profile0=new Profile();
            profile0.setFirstName("FIRSTNAME");
            profile0.setLastName("LASTNAME");
            profile0.setAge("AGE");

            Profile profile1=new Profile();
            profile1.setFirstName("Narayana");
            profile1.setLastName("Ragi");
            profile1.setAge("30");

            Profile profile2=new Profile();
            profile2.setFirstName("Kumar");
            profile2.setLastName("Chitra");
            profile2.setAge("40");

            Profile profile3=new Profile();
            profile3.setFirstName("Swamy");
            profile3.setLastName("Bathala");
            profile3.setAge("30");

            List<Profile> csvData = new ArrayList<Profile>();
            csvData.add(profile0);
            csvData.add(profile1);
            csvData.add(profile2);
            csvData.add(profile3);

            for(Profile profile:csvData){
                writer.append(profile.getFirstName());
                writer.append(Comma);
                writer.append(profile.getLastName());
                writer.append(Comma);
                writer.append(profile.getAge());
                writer.append(newLine);
            }
            writer.close();
            System.out.println("CSV file created succesfully.");
        } catch (Exception e) {
            System.out.println("exception :" + e.getMessage());
        }

    }
}

Output

CSV file created succesfully.

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 By View Object and List by using opencsv jar file.