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
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)
}
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
-
1Why is
writeCsvFile
labelledprivate
? 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? Apr 14, 2022 at 1:16 -
1@SqueezeOJ it should not have been private - sorry for that. Thanks for pointing it out.– FilipApr 14, 2022 at 8:14
-
1