CSV Files

A CSV (Comma Separated Values) file is a text based format that represents the data typically found in a spreadsheet or a database table.

It is a common format for data interchange as it is simple, compact and used everywhere. It will open into Excel with a double click and nearly all databases have a tool to allow import from CSV. It is also readily parse-able with simple code.

The basic format is defined by a rows of column data. Each row is terminated by a newline to begin the next row. Within the row each column is distinguished by a comma.

Data within each column can be double quoted to escape embedded commas in the data. Embedded double quotes are escaped with a pair of double quote characters.

CSV files are also called as flat files, as CSV files contains only simple formated 2 Dimensional tables, Also you donot not sophisticated softwares to handle CSV. You just need simple text editor to manipulate the CSV files.


We can handle the CSV file using below packages with Kotlin:

  • Apache Commons CSV
  • Open CSV

Apache Commons CSV Integration

First of all, you need to add apache-commons-csv dependency in your project. If you use maven, then add the following dependency to your pom.xml file.


<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.5</version>
</dependency>			


For Jar file please got to : https://commons.apache.org/proper/commons-csv/download_csv.cgi, download the zip/tar.gz file under binaries section and add the jar into eclipse with Externar Jars.

Sample CSV Files

Please save the below csv content in your local system with .csv extension

CSV file without header


Name,Product,Description
karthiQ,chercher tech,tutorial
larry page,google,search engine
gates,microsoft,operating system			


CSV file with header


karthiQ,chercher tech,tutorial
larry page,google,search engine
gates,microsoft,operating system			

Write Excel in kotlin

Reading a CSV file with Column Index [ Apache Commons CSV]

We can Read the CSv file using Apache Commons CSV packages, there could be two kind of CSV file.

  • CSV file with Header
  • CSV file without Header

In this Program, I will be using the CSV file without header, follow below steps to read the csv file using Apache Commons CSV package.

Steps to Read CSV file :


1. Create the CSV file and store it in your local machine.

2. Create a new BufferReader object, using the Files class and pass the above CSV file as parameter.


// read the file
val reader = Files.newBufferedReader(Paths.get(CSV_File_Path))			


3. Now All the details are stored in BufferReader object. To parse the BufferReader object into comma seperated values, we have to create object for CSV parser. We have to pass what we are going to parse, and what is the delimeter for parsing (separator)


// parse the file into csv values
val csvParser = CSVParser(reader, CSVFormat.DEFAULT)		


4. Now all the data is loaded into CSVparse object as table like rows and columns, now we have to iterate over every row present in it. We can access the column using index, along with get() method Complete prgram for reading CSV file with column index


import org.apache.commons.csv.CSVFormat
import org.apache.commons.csv.CSVParser
import java.nio.file.Paths
import java.nio.file.Files
fun main(args: Array) {
    val CSV_File_Path = "C:\\Users\\user\\Desktop\\q.csv"
    // read the file
    val reader = Files.newBufferedReader(Paths.get(CSV_File_Path))
    // parse the file into csv values
    val csvParser = CSVParser(reader, CSVFormat.DEFAULT)
    for (csvRecord in csvParser) {
        // Accessing Values by Column Index
        val name = csvRecord.get(0)
        val product = csvRecord.get(1)
        val description = csvRecord.get(2)
        // print the value to console
        System.out.println("Record No - " + csvRecord.getRecordNumber())
        println("---------------")
        println("Name : $name")
        println("Product : $product")
        println("Description : $description")
        println("---------------\n\n")
    }
}			


Read Multiple Property Files

Reading a CSV file with Column Name [ Apache commons CSV] in Kotlin

In above example, we have seen how to read the CSV file with index of the column in kotlin, but when we read like that we may not get the exact information what row we are reading.

To make it more readable we should create it with column names, so that we can call the values by its column name.


We have to create headers to call the values with its name, We can set the header while creating the CSVParser.

For this example, I am using CSV file without header


val csvParser = CSVParser(reader, CSVFormat.DEFAULT
            .withHeader("Name", "Product", "Description")
            .withIgnoreHeaderCase()
            .withTrim())		


Complete program for reading CSV file with Column Names in kotlin.


import org.apache.commons.csv.CSVFormat
import org.apache.commons.csv.CSVParser
import java.nio.file.Paths
import java.nio.file.Files
fun main(args: Array) {
    val CSV_File_Path = "C:\\Users\\user\\Desktop\\q.csv"
    // read the file
    val reader = Files.newBufferedReader(Paths.get(CSV_File_Path))
    val csvParser = CSVParser(reader, CSVFormat.DEFAULT
            .withHeader("Name", "Product", "Description")
            .withIgnoreHeaderCase()
            .withTrim())
    for (csvRecord in csvParser) {
        // Accessing values by the names assigned to each column
        val name = csvRecord.get("Name")
        val product = csvRecord.get("Product")
        val description = csvRecord.get("Description")
        println("Record No - " + csvRecord.recordNumber)
        println("---------------")
        println("Name : $name")
        println("Product : $product")
        println("Description : $description")
        println("---------------\n\n")
    }
}			


Kotlin Create File

Reading a CSV file with Header Auto-detection

In last example, we have seen how to create Column names for the CSV files, but most of the time CSV files do come with headers.

When we have headers in CSV file, we may need to convert them into column names or we have to tell the CSV parse that this files has Headers.


val csvParser = CSVParser(reader, CSVFormat.DEFAULT
            .withFirstRecordAsHeader()
            .withIgnoreHeaderCase()
            .withTrim())			


Complete program for reading CSV files with headers in kotlin


import org.apache.commons.csv.CSVFormat
import org.apache.commons.csv.CSVParser
import java.nio.file.Paths
import java.nio.file.Files
fun main(args: Array) {
    val CSV_File_Path = "C:\\Users\\user\\Desktop\\q_header.csv"
    // read the file
    val reader = Files.newBufferedReader(Paths.get(CSV_File_Path))
    val csvParser = CSVParser(reader, CSVFormat.DEFAULT
            .withFirstRecordAsHeader()
            .withIgnoreHeaderCase()
            .withTrim())
    for (csvRecord in csvParser) {
        // Accessing values by the names assigned to each column
        val name = csvRecord.get("Name")
        val product = csvRecord.get("Product")
        val description = csvRecord.get("Description")
        println("Record No - " + csvRecord.recordNumber)
        println("---------------")
        println("Name : $name")
        println("Product : $product")
        println("Description : $description")
        println("---------------\n\n")
    }
}			


KFunction in Kotlin Reflection

Generating a CSV file

Sometimes we may need to create the CSV files based on the values present in the website

Steps to Create CSV file :


1. Create the BufferedWriter object for the file to which we are going to write our content, This file may or may not exist in File system.

If File exists in file system then it will be replaced, if file is not present then new file will be created with the given name


    val CSV_File_Path = "C:\\Users\\user\\Desktop\\q1.csv"
    val writer = Files.newBufferedWriter(Paths.get(CSV_File_Path))		


2. Create the object for CSVPrinter class and also specify what is the delimiter and headers of the file.


val csvPrinter = CSVPrinter(writer, CSVFormat.DEFAULT
            .withHeader("ID", "Name", "Designation", "Company"))			


3.Using printRecord method you can push the values into the file.


csvPrinter.printRecord("1", "karthiq", "admin", "chercher tech")			


4. The fulsh() method pushes the file and its content into local system. Complete program for writing the data into csv files with Kotlin


import org.apache.commons.csv.CSVFormat
import java.nio.file.Paths
import java.nio.file.Files
import org.apache.commons.csv.CSVPrinter
fun main(args: Array) {
    val CSV_File_Path = "C:\\Users\\user\\Desktop\\q1.csv"
    val writer = Files.newBufferedWriter(Paths.get(CSV_File_Path))
    val csvPrinter = CSVPrinter(writer, CSVFormat.DEFAULT
            .withHeader("ID", "Name", "Designation", "Company"))
    csvPrinter.printRecord("1", "karthiq", "admin", "chercher tech")
    csvPrinter.printRecord("2", "Jeff", "CEO", "Amazon")
    csvPrinter.printRecord("3", "Tim", "CEO", "Apple")
    csvPrinter.flush()
    csvPrinter.close()
}			


Generics at RunTime | Type erasure

aaaaaaaaaaaaa
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Selenium Online Training : Our next online training course for Selenium with Java starts from 17th December 2018.

You can attend first 3 classes for free, the total course fee is INR 10,000

The course time would be 8.00 PM(IST) for the first three classes

If you are interested to learn, then you can join the course by sending email to chercher.tech@gmail.com

or Register below


 
Join My Facebook Group
Join Group