0

I am new to Scala and programming in general. How would I go to write a list into a .csv file using Scala?

So I have a list of objects...

List[test] = List(test(Group1,lol,1,2,3),test(Group2,lel,4,5,6)....)

how would I export it to a .csv with 4 columns, and each line having the attributes of an object?

Any help is appreciated.

1
  • Because of so many issues, even in the presence of an RFC for the .csv MIME-type, I strongly suggest you use a well-maintained RFC driven native Scala library which optimally handles this problem, kantan.csv: nrinaudo.github.io/kantan.csv Commented Aug 30, 2020 at 20:25

2 Answers 2

2

Case classes are instances of Product that offers a nice way to iterate through all of the fields as .productIterator.

The idea is that you convert all fields to strings, then escape backslashes and double-quotes if there are any, then join them all together, double-quoted and separated by commas, and then glue everything with a new-line:

list
 .map { 
    _.productIterator
     .map(_.toString)
     .map(_.replaceAll("\\", "\\\\"))
     .map(_.replaceAll("\"", "\\\""))
     .mkString("\"", "\",\"", "\"")
 }.mkString("\n")
Sign up to request clarification or add additional context in comments.

Comments

0

I recommend using an existing library: https://github.com/melrief/PureCSV
Use SBT for resolving the dependency: http://www.scala-sbt.org/
Files:
* ./build.sbt
* ./OutputCsv.scala

build.sbt

name := "parse-csv"
version := "1.0.0"
libraryDependencies ++= Seq("com.github.melrief" %% "purecsv" % "0.1.1")

OutputCsv.scala

import purecsv.safe._

object OutputCsv extends App {
    case class Test(group: String, message: String, age: Int)
    val tests = List(Test("Group1", "lol", 1), Test("Group2", "lel", 4))

    println(tests.toCSV()) // just for debug purposes
    tests.writeCSVToFileName("/tmp/example.csv", header=Some(Seq("group", "message", "age")))
}

sbt run will execute the file

1 Comment

That is great feedback! I have managed everything you mention except the sbt run part. I am using IntelliJ here and when running the code I only get import purecsv.safe._ defined module OutputCsv So I suppose it does not run

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.