Comma-Separated Values - CSV

Comma-Separated Values are used as interchange format for tabular data of text. This format is supported by most spreadsheet applications and may be used as database extraction format.

Despite the name the values are often separated by a semicolon ;.

Even though the format is interpreted differently there exists a formal specification in RFC4180.

The format uses three different characters to structure the data:

  • Field Delimiter - separates the columns from each other (e.g. , or ;)
  • Quote - marks columns that may contain other structuring characters (such as Field Delimiters or line break) (e.g. ")
  • Escape Character - used to escape Field Delimiters in columns (e.g. \)

Lines are separated by either Line Feed (\n = ASCII 10) or Carriage Return and Line Feed (\r = ASCII 13 + \n = ASCII 10).

Project Info: Alpakka CSV
Artifact
com.lightbend.akka
akka-stream-alpakka-csv
1.0-M2
JDK versions
OpenJDK 8
Scala versions2.12.7, 2.11.12
JPMS module nameakka.stream.alpakka.csv
License
Readiness level
Community-driven
Since 0.8, 2017-05-05
Home pagehttps://doc.akka.io/docs/alpakka/current/
API documentation
Forums
Release notesIn the documentation
IssuesGithub issues
Sourceshttps://github.com/akka/alpakka

Artifacts

sbt
libraryDependencies += "com.lightbend.akka" %% "akka-stream-alpakka-csv" % "1.0-M2"
Maven
<dependency>
  <groupId>com.lightbend.akka</groupId>
  <artifactId>akka-stream-alpakka-csv_2.12</artifactId>
  <version>1.0-M2</version>
</dependency>
Gradle
dependencies {
  compile group: 'com.lightbend.akka', name: 'akka-stream-alpakka-csv_2.12', version: '1.0-M2'
}

The table below shows direct dependencies of this module and the second tab shows all libraries it depends on transitively.

Direct dependencies
OrganizationArtifactVersionLicense
com.typesafe.akkaakka-stream_2.122.5.19Apache License, Version 2.0
org.scala-langscala-library2.12.7BSD 3-Clause
Dependency tree
com.typesafe.akka    akka-stream_2.12    2.5.19    Apache License, Version 2.0
    com.typesafe.akka    akka-actor_2.12    2.5.19    Apache License, Version 2.0
        com.typesafe    config    1.3.3    Apache License, Version 2.0
        org.scala-lang.modules    scala-java8-compat_2.12    0.8.0    BSD 3-clause
            org.scala-lang    scala-library    2.12.7    BSD 3-Clause
        org.scala-lang    scala-library    2.12.7    BSD 3-Clause
    com.typesafe.akka    akka-protobuf_2.12    2.5.19    Apache License, Version 2.0
        org.scala-lang    scala-library    2.12.7    BSD 3-Clause
    com.typesafe    ssl-config-core_2.12    0.3.6    Apache-2.0
        com.typesafe    config    1.3.3    Apache License, Version 2.0
        org.scala-lang.modules    scala-parser-combinators_2.12    1.1.1    BSD 3-clause
            org.scala-lang    scala-library    2.12.7    BSD 3-Clause
        org.scala-lang    scala-library    2.12.7    BSD 3-Clause
    org.reactivestreams    reactive-streams    1.0.2    CC0
    org.scala-lang    scala-library    2.12.7    BSD 3-Clause
org.scala-lang    scala-library    2.12.7    BSD 3-Clause

CSV parsing

CSV parsing offers a flow that takes a stream of akka.util.ByteString and issues a stream of lists of ByteString.

The incoming data must contain line ends to allow line base framing. The CSV special characters can be specified (as bytes), suitable values are available as constants in CsvParsing.

Note

The current parser is limited to byte-based character sets (UTF-8, ISO-8859-1, ASCII) and can’t parse double-byte encodings (e.g. UTF-16).

The parser accepts Byte Order Mark (BOM) for UTF-8, but will fail for UTF-16 and UTF-32 Byte Order Marks.

Scala
import akka.stream.alpakka.csv.scaladsl.CsvParsing

val flow: Flow[ByteString, List[ByteString], NotUsed]
  = CsvParsing.lineScanner(delimiter, quoteChar, escapeChar)
Java
Flow<ByteString, Collection<ByteString>, NotUsed> flow =
    CsvParsing.lineScanner(delimiter, quoteChar, escapeChar);

In this sample we read a single line of CSV formatted data into a list of column elements:

Scala
import akka.stream.alpakka.csv.scaladsl.CsvParsing

Source.single(ByteString("eins,zwei,drei\n"))
  .via(CsvParsing.lineScanner())
  .runWith(Sink.head)

result should be(List(ByteString("eins"), ByteString("zwei"), ByteString("drei")))
Java

Source.single(ByteString.fromString("eins,zwei,drei\n")) .via(CsvParsing.lineScanner()) .runWith(Sink.head(), materializer);

To convert the ByteString columns as String, a map operation can be added to the Flow:

Scala
import akka.stream.alpakka.csv.scaladsl.CsvParsing

Source.single(ByteString("eins,zwei,drei\n"))
  .via(CsvParsing.lineScanner())
  .map(_.map(_.utf8String))
  .runWith(Sink.head)

result should be(List("eins", "zwei", "drei"))
Java

Source.single(ByteString.fromString("eins,zwei,drei\n")) .via(CsvParsing.lineScanner()) .map(line -> line.stream().map(ByteString::utf8String).collect(Collectors.toList())) .runWith(Sink.head(), materializer);

CSV conversion into a map

The column-based nature of CSV files can be used to read it into a map of column names and their ByteString values, or alternatively to String values. The column names can be either provided in code or the first line of data can be interpreted as the column names.

Scala
import akka.stream.alpakka.csv.scaladsl.CsvToMap

// keep values as ByteString
val flow1: Flow[List[ByteString], Map[String, ByteString], NotUsed]
  = CsvToMap.toMap()

val flow2: Flow[List[ByteString], Map[String, ByteString], NotUsed]
  = CsvToMap.toMap(StandardCharsets.UTF_8)

val flow3: Flow[List[ByteString], Map[String, ByteString], NotUsed]
  = CsvToMap.withHeaders("column1", "column2", "column3")

// values as String (decode ByteString)
val flow4: Flow[List[ByteString], Map[String, String], NotUsed]
= CsvToMap.toMapAsStrings(StandardCharsets.UTF_8)

val flow5: Flow[List[ByteString], Map[String, String], NotUsed]
= CsvToMap.withHeadersAsStrings(StandardCharsets.UTF_8, "column1", "column2", "column3")
Java
// keep values as ByteString
Flow<Collection<ByteString>, Map<String, ByteString>, ?> flow1 = CsvToMap.toMap();

Flow<Collection<ByteString>, Map<String, ByteString>, ?> flow2 =
    CsvToMap.toMap(StandardCharsets.UTF_8);

Flow<Collection<ByteString>, Map<String, ByteString>, ?> flow3 =
    CsvToMap.withHeaders("column1", "column2", "column3");

// values as String (decode ByteString)
Flow<Collection<ByteString>, Map<String, String>, ?> flow4 =
    CsvToMap.toMapAsStrings(StandardCharsets.UTF_8);

Flow<Collection<ByteString>, Map<String, String>, ?> flow5 =
    CsvToMap.withHeadersAsStrings(StandardCharsets.UTF_8, "column1", "column2", "column3");

This example uses the first line (the header line) in the CSV data as column names:

Scala
import akka.stream.alpakka.csv.scaladsl.{CsvParsing, CsvToMap}

// values as ByteString
Source
  .single(ByteString("""eins,zwei,drei
                       |11,12,13
                       |21,22,23
                       |""".stripMargin))
  .via(CsvParsing.lineScanner())
  .via(CsvToMap.toMap())
  .runWith(Sink.seq)

result should be(
  Seq(
    Map("eins" -> ByteString("11"), "zwei" -> ByteString("12"), "drei" -> ByteString("13")),
    Map("eins" -> ByteString("21"), "zwei" -> ByteString("22"), "drei" -> ByteString("23"))
  )
)

// values as String
Source
  .single(ByteString("""eins,zwei,drei
                       |11,12,13
                       |21,22,23
                       |""".stripMargin))
  .via(CsvParsing.lineScanner())
  .via(CsvToMap.toMapAsStrings())
  .runWith(Sink.seq)

result should be(
  Seq(
    Map("eins" -> "11", "zwei" -> "12", "drei" -> "13"),
    Map("eins" -> "21", "zwei" -> "22", "drei" -> "23")
  )
)
Java

// values as ByteString Source.single(ByteString.fromString("eins,zwei,drei\n1,2,3")) .via(CsvParsing.lineScanner()) .via(CsvToMap.toMap(StandardCharsets.UTF_8)) .runWith(Sink.head(), materializer); assertThat(map.get("eins"), equalTo(ByteString.fromString("1"))); assertThat(map.get("zwei"), equalTo(ByteString.fromString("2"))); assertThat(map.get("drei"), equalTo(ByteString.fromString("3"))); // values as String Source.single(ByteString.fromString("eins,zwei,drei\n1,2,3")) .via(CsvParsing.lineScanner()) .via(CsvToMap.toMapAsStrings(StandardCharsets.UTF_8)) .runWith(Sink.head(), materializer); assertThat(map.get("eins"), equalTo("1")); assertThat(map.get("zwei"), equalTo("2")); assertThat(map.get("drei"), equalTo("3"));

This sample will generate the same output as above, but the column names are specified in the code:

Scala
import akka.stream.alpakka.csv.scaladsl.{CsvParsing, CsvToMap}

// values as ByteString
Source
  .single(ByteString(
    """11,12,13
      |21,22,23
      |""".stripMargin))
  .via(CsvParsing.lineScanner())
  .via(CsvToMap.withHeaders("eins", "zwei", "drei"))
  .runWith(Sink.seq)

result should be(
  Seq(
    Map("eins" -> ByteString("11"), "zwei" -> ByteString("12"), "drei" -> ByteString("13")),
    Map("eins" -> ByteString("21"), "zwei" -> ByteString("22"), "drei" -> ByteString("23"))
  )
)

// values as String
Source
  .single(ByteString("""11,12,13
                       |21,22,23
                       |""".stripMargin))
  .via(CsvParsing.lineScanner())
  .via(CsvToMap.withHeadersAsStrings(StandardCharsets.UTF_8, "eins", "zwei", "drei"))
  .runWith(Sink.seq)

result should be(
  Seq(
    Map("eins" -> "11", "zwei" -> "12", "drei" -> "13"),
    Map("eins" -> "21", "zwei" -> "22", "drei" -> "23")
  )
)
Java

// values as ByteString Source.single(ByteString.fromString("1,2,3")) .via(CsvParsing.lineScanner()) .via(CsvToMap.withHeaders("eins", "zwei", "drei")) .runWith(Sink.head(), materializer); assertThat(map.get("eins"), equalTo(ByteString.fromString("1"))); assertThat(map.get("zwei"), equalTo(ByteString.fromString("2"))); assertThat(map.get("drei"), equalTo(ByteString.fromString("3"))); // values as String Source.single(ByteString.fromString("1,2,3")) .via(CsvParsing.lineScanner()) .via(CsvToMap.withHeadersAsStrings(StandardCharsets.UTF_8, "eins", "zwei", "drei")) .runWith(Sink.head(), materializer); assertThat(map.get("eins"), equalTo("1")); assertThat(map.get("zwei"), equalTo("2")); assertThat(map.get("drei"), equalTo("3"));

CSV formatting

To emit CSV files immutable.Seq[String] can be formatted into ByteString e.g to be written to file. The formatter takes care of quoting and escaping.

Certain CSV readers (e.g. Microsoft Excel) require CSV files to indicate their character encoding with a Byte Order Mark (BOM) in the first bytes of the file. Choose an appropriate Byte Order Mark matching the selected character set from the constants in ByteOrderMark (Unicode FAQ on Byte Order Mark).

Scala
val flow: Flow[immutable.Seq[String], ByteString, _]
  = CsvFormatting.format(delimiter,
                         quoteChar,
                         escapeChar,
                         endOfLine,
                         CsvQuotingStyle.Required,
                         charset = StandardCharsets.UTF_8,
                         byteOrderMark = None)
Java
Flow<Collection<String>, ByteString, ?> flow1 = CsvFormatting.format();

Flow<Collection<String>, ByteString, ?> flow2 =
    CsvFormatting.format(
        delimiter,
        quoteChar,
        escapeChar,
        endOfLine,
        CsvQuotingStyle.REQUIRED,
        charset,
        byteOrderMark);

This example uses the default configuration:

  • Delimiter: comma (,)
  • Quote char: double quote (")
  • Escape char: backslash (\)
  • Line ending: Carriage Return and Line Feed (\r = ASCII 13 + \n = ASCII 10)
  • Quoting style: quote only if required
  • Charset: UTF-8
  • No Byte Order Mark
Scala
import akka.stream.alpakka.csv.scaladsl.CsvFormatting

Source
  .single(List("eins", "zwei", "drei"))
  .via(CsvFormatting.format())
  .runWith(Sink.head)
Java
Source.single(Arrays.asList("one", "two", "three", "four"))
    .via(CsvFormatting.format())
    .runWith(Sink.head(), materializer);
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.