All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.Csv.kt Maven / Gradle / Ivy

There is a newer version: 0.13
Show newest version
/** 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