5

I am able to find method for exporting Java's list of POJO to csv but unable to find a method to export Kotlin's list of data class to CSV.

2 Answers 2

3

This can be achieved using basic Kotlin instead of an external library.

data class

data class Category(
    val id: String,
    val name: String,
)

utility function

fun <T> csvOf(
    headers: List<String>,
    data: List<T>,
    itemBuilder: (T) -> List<String>
) = buildString {
    append(headers.joinToString(",") { "\"$it\"" })
    append("\n")
    data.forEach { item ->
        append(itemBuilder(item).joinToString(",") { "\"$it\"" })
        append("\n")
    }
}

usage

fun main() {
    val firstCategory = Category(0, "Phone")
    val secondCategory = Category(1, "Laptop")
    val categories = listOf(firstCategory, secondCategory)
    val csv = csvOf(
        listOf("id", "name"),
        categories
    ) {
        listOf(it.id.toString(), it.name)
    }
    println(csv)
}
1

You can use the solution offered by this medium article:

To sum up

You can create a simple generic function

import java.io.FileWriter

inline fun <reified T> writeCsvFile(data: Collection<T>, fileName: String) {
    FileWriter(fileName).use { writer ->
        csvMapper.writer(csvMapper.schemaFor(T::class.java).withHeader())
                .writeValues(writer)
                .writeAll(data)
                .close()
    }
}

I tested it with the following dependencies:

com.fasterxml.jackson.dataformat:jackson-dataformat-csv:2.11.1
com.fasterxml.jackson.module:jackson-module-kotlin:2.12.5
3
  • 1
    Why is writeCsvFile labelled private? As a result, I don't seem to be able to access it from my code and can't get it to work. Any advice?
    – SqueezeOJ
    Apr 14, 2022 at 1:16
  • 1
    @SqueezeOJ it should not have been private - sorry for that. Thanks for pointing it out.
    – Filip
    Apr 14, 2022 at 8:14
  • 1
    The Jackson library is now archived
    – Vince
    Jan 9 at 6:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.