commonMain.Csv.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of csv-jvm Show documentation
Show all versions of csv-jvm Show documentation
Tiny KMP library for parsing, building and generating CSV files
/** Copyright 2023 Halfbit GmbH, Sergej Shafarenka */
package de.halfbit.csv
public class Csv(
public val rows: List>,
) {
// Multiline issue: https://stackoverflow.com/questions/2668678/importing-csv-with-line-breaks-in-excel-2007
public fun toCsvText(
newLine: NewLine = NewLine.LF,
escapeWhitespaces: Boolean = false,
): String =
rows.fold("") { acc, row ->
val rowText =
row
.fold("") { rowAcc, value ->
val escapedValue = value.escapeCsvValue(escapeWhitespaces)
"$rowAcc$escapedValue,"
}
.removeSuffix(",")
"$acc$rowText${newLine.value}"
}
}
public enum class NewLine(
public val value: String,
) {
LF("\n"),
CRLF("\r\n")
}
// https://en.wikipedia.org/wiki/Comma-separated_values#Basic_rules
private fun String.escapeCsvValue(
escapeWhitespaces: Boolean,
): String =
when {
isEmpty() -> "\"\""
contains(",") || contains("\n") || (escapeWhitespaces && contains(" ")) -> {
val escapedQuoted = replace("\"", "\"\"")
"\"${escapedQuoted}\""
}
else -> this
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy