How to write data in CSV format

Posted by Java developer blog on June 24, 2020

Overview

Sometimes we need to save data from a database in a file. For example, we could write data in a CSV format. In the post, we are to use OpenCSV library to write data in CSV format.

OpenCSV usage example

Firstly, add OpenCSV library from maven repository.

Secondly, create CSVWriter with a file name as argument:

1
val writer = CSVWriter(FileWriter(fileName))

Thirdly, you could use writer to write data:

1
writer.writeNext(row.toTypedArray())

You could see the whole example below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import com.opencsv.CSVWriter
import java.io.FileWriter

fun main() {
    val fileName = "example.csv"
    val writer = CSVWriter(FileWriter(fileName))
    val rows = listOf(
        listOf("name", "age"),
        listOf("Mark", "20"),
        listOf("Jane", "22")
    )
    writer.use {
        for (row in rows) {
            writer.writeNext(row.toTypedArray())
        }
    }
}

Other CSV libraries

You could find more information about other CSV libraries here.

Conclusion

We have discussed how to write data in CSV format. You could check out the source code here.