Skip to content

3.09 CSV Output of a Seq[caseClass], Seq[TupleN] or CollSeq

Boris Shilov edited this page Jun 21, 2019 · 7 revisions

CSV Output

An implict class adds a writeCsv and csvIterator method to any Seq of case classes, tuples or CollSeq. writeCsv takes a java.io.Writer. Importing the io package brings the conversion into scope or you can import io.Utils.CsvOutput manually.

Using writeCsv
val w= new java.io.StringWriter

CollSeq((1,2,3.5,"hello"),
        (5,6,7.7,"dude")).writeCsv(w)

w.toString
res7: String =
"1,2,3.5,"hello"
5,6,7.7,"""dude"""
Custom rendering

You can control how your data is rendered by supplying a CsvRenderer which is a PartialFunction[Any,String]. Your renderer is applied first and if there is no match the built in renderer is then applied.

CollSeq((1,2,3.5,Some("hello")),
        (5,6,7.7,None)).csvIterator.foreach(println _)

1,2,3.5,"hello"
5,6,7.7,

val myRenderer:CsvRenderer = {case None=> "N/A"}

CollSeq((1,2,3.5,Some("hello")),
        (5,6,7.7,None)).csvIterator(renderer=myRenderer).foreach(println _)

1,2,3.5,"hello"
5,6,7.7,N/A

There are some prebuilt renderers in the Utils object: naRenderer and singleQuoteRenderer.

You can chain renders using the PartialFunction andThen capability.