{"id":13428893,"url":"https://github.com/jsoizo/kotlin-csv","last_synced_at":"2025-03-16T02:30:45.433Z","repository":{"id":40456896,"uuid":"200859123","full_name":"jsoizo/kotlin-csv","owner":"jsoizo","description":"Pure Kotlin CSV Reader/Writer","archived":false,"fork":false,"pushed_at":"2024-12-31T05:19:25.000Z","size":574,"stargazers_count":663,"open_issues_count":21,"forks_count":50,"subscribers_count":8,"default_branch":"main","last_synced_at":"2025-03-03T21:01:52.743Z","etag":null,"topics":["csv","dsl","kotlin","kotlin-csv","kotlin-multiplatform"],"latest_commit_sha":null,"homepage":"","language":"Kotlin","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jsoizo.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"jsoizo"}},"created_at":"2019-08-06T13:39:49.000Z","updated_at":"2025-02-28T07:30:18.000Z","dependencies_parsed_at":"2024-01-22T16:33:59.143Z","dependency_job_id":"49a42536-7317-48c0-b313-1d8cc26d863c","html_url":"https://github.com/jsoizo/kotlin-csv","commit_stats":{"total_commits":333,"total_committers":27,"mean_commits":"12.333333333333334","dds":"0.18918918918918914","last_synced_commit":"12d008ba9948eb8c54b5c7ed56939192abdb68dd"},"previous_names":["jsoizo/kotlin-csv"],"tags_count":39,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jsoizo%2Fkotlin-csv","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jsoizo%2Fkotlin-csv/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jsoizo%2Fkotlin-csv/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jsoizo%2Fkotlin-csv/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jsoizo","download_url":"https://codeload.github.com/jsoizo/kotlin-csv/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243815611,"owners_count":20352197,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["csv","dsl","kotlin","kotlin-csv","kotlin-multiplatform"],"created_at":"2024-07-31T01:01:08.092Z","updated_at":"2025-03-16T02:30:44.947Z","avatar_url":"https://github.com/jsoizo.png","language":"Kotlin","funding_links":["https://github.com/sponsors/jsoizo"],"categories":["Libraries","Multiplatform"],"sub_categories":["🔧 Utils","Android samples"],"readme":"\u003ch1 align=\"center\"\u003ekotlin-csv\u003c/h1\u003e\n\n\u003cp\u003e\n  \u003cimg alt=\"Version\" src=\"https://img.shields.io/badge/version-1.10.0-blue.svg?cacheSeconds=2592000\" /\u003e\n  \u003ca href=\"https://github.com/jsoizo/kotlin-csv/blob/master/LICENSE\"\u003e\n    \u003cimg alt=\"License: Apache License 2.0\" src=\"https://img.shields.io/badge/License-Apache License 2.0-yellow.svg\" target=\"_blank\" /\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://codecov.io/gh/jsoizo/kotlin-csv\"\u003e\n    \u003cimg src=\"https://codecov.io/gh/jsoizo/kotlin-csv/branch/master/graph/badge.svg\" alt=\"codecov\" /\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://www.codefactor.io/repository/github/jsoizo/kotlin-csv\"\u003e\n    \u003cimg src=\"https://www.codefactor.io/repository/github/jsoizo/kotlin-csv/badge\" alt=\"CodeFactor\" /\u003e\n  \u003c/a\u003e\n\u003c/p\u003e\n\nPure Kotlin CSV Reader/Writer.\n\n# Design goals\n\n### 1. Simple interface\n\n* easy to setup\n* use DSL so easy to read\n\n### 2. Automatic handling of I/O\n\n* in Java, we always need to close file. but it's boilerplate code and not friendly for non-JVM user.\n* provide interfaces which automatically close file without being aware.\n\n### 3. Multiplatform\n\n* Kotlin Multiplatform projects support.\n\n# Usage\n\n## Download\n\n### Gradle\n\nfor Kotlin DSL\n\n```kotlin\nimplementation(\"com.jsoizo:kotlin-csv-jvm:1.10.0\") // for JVM platform\nimplementation(\"com.jsoizo:kotlin-csv-js:1.10.0\") // for Kotlin JS platform\n```\n\nfor Gradle DSL\n\n```groovy\nimplementation 'com.jsoizo:kotlin-csv-jvm:1.10.0' // for JVM platform\nimplementation 'com.jsoizo:kotlin-csv-js:1.10.0' // for Kotlin JS platform\n```\n\n### Maven\n\n```maven\n\u003cdependency\u003e\n  \u003cgroupId\u003ecom.jsoizo\u003c/groupId\u003e\n  \u003cartifactId\u003ekotlin-csv-jvm\u003c/artifactId\u003e\n  \u003cversion\u003e1.10.0\u003c/version\u003e\n\u003c/dependency\u003e\n\u003cdependency\u003e\n  \u003cgroupId\u003ecom.jsoizo\u003c/groupId\u003e\n  \u003cartifactId\u003ekotlin-csv-js\u003c/artifactId\u003e\n  \u003cversion\u003e1.10.0\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n### [kscript](https://github.com/holgerbrandl/kscript)\n\n```kotlin\n@file:DependsOn(\"com.jsoizo:kotlin-csv-jvm:1.10.0\") // for JVM platform\n@file:DependsOn(\"com.jsoizo:kotlin-csv-js:1.10.0\") // for Kotlin JS platform\n```\n\n## Examples\n\n### CSV Read examples\n\n#### Simple case\n\nYou can read csv file from `String`, `java.io.File` or `java.io.InputStream` object.  \nNo need to do any I/O handling. (No need to call `use`, `close` and `flush` method.)\n\n```kotlin\n// read from `String`\nval csvData: String = \"a,b,c\\nd,e,f\"\nval rows: List\u003cList\u003cString\u003e\u003e = csvReader().readAll(csvData)\n\n// read from `java.io.File`\nval file: File = File(\"test.csv\")\nval rows: List\u003cList\u003cString\u003e\u003e = csvReader().readAll(file)\n```\n\n#### Read with header\n\n```kotlin\nval csvData: String = \"a,b,c\\nd,e,f\"\nval rows: List\u003cMap\u003cString, String\u003e\u003e = csvReader().readAllWithHeader(csvData)\nprintln(rows) //[{a=d, b=e, c=f}]\n```\n\n#### Read as `Sequence`\n\n`Sequence` type allows to execute lazily.\u003cbr /\u003e\nIt starts to process each rows before reading all row data.\n\nLearn more about the `Sequence` type on [Kotlin's official documentation](https://kotlinlang.org/docs/reference/sequences.html).\n\n```kotlin\ncsvReader().open(\"test1.csv\") {\n    readAllAsSequence().forEach { row: List\u003cString\u003e -\u003e\n        //Do something\n        println(row) //[a, b, c]\n    }\n}\n\ncsvReader().open(\"test2.csv\") {\n    readAllWithHeaderAsSequence().forEach { row: Map\u003cString, String\u003e -\u003e\n        //Do something\n        println(row) //{id=1, name=jsoizo}\n    }\n}\n```\n\nNOTE: `readAllAsSequence` and `readAllWithHeaderAsSequence` methods can only be called within the `open` lambda block.\nThe input stream is closed after the `open` lambda block.\n\n#### Read line by line\n\nIf you want to handle line-by-line, you can do it by using `open` method. Use `open` method and then use `readNext`\nmethod inside nested block to read row.\n\n```kotlin\ncsvReader().open(\"test.csv\") {\n    readNext()\n}\n```\n\n#### Read in a `Suspending Function`\n\n```kotlin\ncsvReader().openAsync(\"test.csv\") {\n    val container = mutalbeListOf\u003cList\u003cString\u003e\u003e()\n    delay(100) //other suspending task\n    readAllAsSequence().asFlow().collect { row -\u003e\n        delay(100) // other suspending task\n        container.add(row)\n    }\n}\n```\n\nNote: `openAsync` can be and only be accessed through a `coroutine` or another `suspending` function\n\n#### Customize\n\nWhen you create CsvReader, you can choose read options:\n\n```kotlin\n// this is tsv reader's option\nval tsvReader = csvReader {\n    charset = \"ISO_8859_1\"\n    quoteChar = '\"'\n    delimiter = '\\t'\n    escapeChar = '\\\\'\n}\n```\n\n| Option                         | default value | description                                                                                                                                                                                                                                                                            |\n|--------------------------------|---------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| logger                         | _no-op_       | Logger instance for logging debug information at runtime.                                                                                                                                                                                                                              |\n| charset                        | `UTF-8`       | Charset encoding. The value must be supported by [java.nio.charset.Charset](https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html).                                                                                                                                  |\n| quoteChar                      | `\"`           | Character used to quote fields.                                                                                                                                                                                                                                                        |\n| delimiter                      | `,`           | Character used as delimiter between each field.\u003cbr /\u003eUse `\"\\t\"` if reading TSV file.                                                                                                                                                                                                   |\n| escapeChar                     | `\"`           | Character to escape quote inside field string.\u003cbr /\u003eNormally, you don't have to change this option.\u003cbr /\u003eSee detail comment on [ICsvReaderContext](src/commonMain/kotlin/com/github/doyaaaaaken/kotlincsv/dsl/context/CsvReaderContext.kt).                                            |\n| skipEmptyLine                  | `false`       | Whether to skip or error out on empty lines.                                                                                                                                                                                                                                           |\n| autoRenameDuplicateHeaders     | `false`       | Whether to auto rename duplicate headers or throw an exception.                                                                                                                                                                                                                        |\n| ~~skipMissMatchedRow~~         | `false`       | Deprecated. Replace with appropriate values in `excessFieldsRowBehaviour` and `insufficientFieldsRowBehaviour`, e.g. both set to `IGNORE`. ~~Whether to skip an invalid row. If `ignoreExcessCols` is true, only rows with less than the expected number of columns will be skipped.~~ |\n| excessFieldsRowBehaviour       | `ERROR`       | Behaviour to use when a row has more fields (columns) than expected. `ERROR` (default), `IGNORE` (skip the row) or `TRIM` (remove the excess fields at the end of the row to match the expected number of fields).                                                                     |\n| insufficientFieldsRowBehaviour | `ERROR`       | Behaviour to use when a row has fewer fields (columns) than expected. `ERROR` (default), `IGNORE` (skip the row) or `EMPTY_STRING` (replace missing fields with an empty string).                                                                                                      |\n\n### CSV Write examples\n\n#### Simple case\n\nYou can start writing csv in one line, no need to do any I/O handling (No need to call `use`, `close` and `flush`\nmethod.):\n\n```kotlin\nval rows = listOf(listOf(\"a\", \"b\", \"c\"), listOf(\"d\", \"e\", \"f\"))\ncsvWriter().writeAll(rows, \"test.csv\")\n\n// if you'd append data on the tail of the file, assign `append = true`.\ncsvWriter().writeAll(rows, \"test.csv\", append = true)\n\n// You can also write into OutpusStream.\ncsvWriter().writeAll(rows, File(\"test.csv\").outputStream())\n```\n\nYou can also write a csv file line by line by `open` method:\n\n```kotlin\nval row1 = listOf(\"a\", \"b\", \"c\")\nval row2 = listOf(\"d\", \"e\", \"f\")\n\ncsvWriter().open(\"test.csv\") {\n    writeRow(row1)\n    writeRow(row2)\n    writeRow(\"g\", \"h\", \"i\")\n    writeRows(listOf(row1, row2))\n}\n```\n\n#### Write in a `Suspending Function`\n\n```kotlin\nval rows = listOf(listOf(\"a\", \"b\", \"c\"), listOf(\"d\", \"e\", \"f\")).asSequence()\ncsvWriter().openAsync(testFileName) {\n    delay(100) //other suspending task\n    rows.asFlow().collect {\n        delay(100) // other suspending task\n        writeRow(it)\n    }\n}\n```\n\n#### Write as String\n\n```kotlin\nval rows = listOf(listOf(\"a\", \"b\", \"c\"), listOf(\"d\", \"e\", \"f\"))\nval csvString: String = csvWriter().writeAllAsString(rows) //a,b,c\\r\\nd,e,f\\r\\n\n```\n\n#### long-running write (manual control for file close)\n\nIf you want to close a file writer manually for performance reasons (e.g. streaming scenario), you can\nuse `openAndGetRawWriter` and get a raw `CsvFileWriter`.  \n**DO NOT forget to `close` the writer!**\n\n```kotlin\nval row1 = listOf(\"a\", \"b\", \"c\")\n\n@OptIn(KotlinCsvExperimental::class)\nval writer = csvWriter().openAndGetRawWriter(\"test.csv\")\nwriter.writeRow(row1)\nwriter.close()\n```\n\n#### Customize\n\nWhen you create a CsvWriter, you can choose write options.\n\n```kotlin\nval writer = csvWriter {\n    charset = \"ISO_8859_1\"\n    delimiter = '\\t'\n    nullCode = \"NULL\"\n    lineTerminator = \"\\n\"\n    outputLastLineTerminator = true\n    quote {\n        mode = WriteQuoteMode.ALL\n        char = '\\''\n    }\n}\n```\n\n| Option | default value | description                         |\n|------------|---------------|-------------------------------------|\n| charset |`UTF-8`| Charset encoding. The value must be supported by [java.nio.charset.Charset](https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html). |\n| delimiter | `,` | Character used as delimiter between each fields.\u003cbr /\u003eUse `\"\\t\"` if reading TSV file. |\n| nullCode | `(empty string)` | Character used when a written field is null value. |\n| lineTerminator | `\\r\\n` | Character used as line terminator. |\n| outputLastLineTerminator | `true` | Output line break at the end of file or not. |\n| prependBOM | `false` | Output BOM (Byte Order Mark) at the beginning of file or not. |\n| quote.char  | `\"` | Character to quote each fields. |\n| quote.mode  | `CANONICAL` | Quote mode. \u003cbr /\u003e- `CANONICAL`: Not quote normally, but quote special characters (quoteChar, delimiter, line feed). This is [the specification of CSV](https://tools.ietf.org/html/rfc4180#section-2).\u003cbr /\u003e- `ALL`: Quote all fields.\u003cbr /\u003e- `NON_NUMERIC`: Quote non-numeric fields. (ex. 1,\"a\",2.3) |\n\n# Links\n\n**Documents**\n\n* [Change Logs](https://github.com/jsoizo/kotlin-csv/releases)\n\n**Libraries which use kotlin-csv**\n\n* [kotlin-grass](https://github.com/blackmo18/kotlin-grass): Csv File to Kotlin Data Class Parser.\n\n# Miscellaneous\n\n## 🤝 Contributing\n\nContributions, [issues](https://github.com/jsoizo/kotlin-csv/issues) and feature requests are welcome!\nIf you have questions, ask away in [Kotlin Slack's](https://kotlinlang.slack.com) `kotlin-csv` room.\n\n## 💻 Development\n\n```sh\ngit clone git@github.com:jsoizo/kotlin-csv.git\ncd kotlin-csv\n./gradlew check\n```\n\n## Show your support\n\nGive a ⭐️ if this project helped you!\n\n## 📝 License\n\nCopyright © 2024 [jsoizo](https://github.com/jsoizo).\nThis project is licensed under [Apache 2.0](LICENSE).\n\n***\n_This project is inspired ❤️ by [scala-csv](https://github.com/tototoshi/scala-csv)_\n\n_This README was generated with ❤️ by [readme-md-generator](https://github.com/kefranabg/readme-md-generator)_\n\n## Acknowledgments\n\nThis project was originally created by [@doyaaaaaken](https://github.com/doyaaaaaken). The initial work and contributions are greatly appreciated.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjsoizo%2Fkotlin-csv","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjsoizo%2Fkotlin-csv","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjsoizo%2Fkotlin-csv/lists"}