How to use Scala-csv Library In Scala
Writing CSV in Scala
Data will be written to a CSV file using the scala-csv library. The data will be in the form of a list of maps with each map representing individual rows. The headers, taken from the keys in the first map, shall precede all other records on file.
Approach:
- Import the necessary libraries.
- Open the CSV file using CSVWriter.
- Define the data as a list of maps.
- Extract headers from the data.
- Convert the data to a sequence of sequences.
- Write the headers and data to the CSV file.
- Close the writer.
Below is the Scala program to write CSV file:
import java.io.File
import com.github.tototoshi.csv._
object WriterExample2 {
def main(args: Array[String]): Unit = {
val writer = CSVWriter.open(new File("output.csv"))
val data = List(
Map("Name" -> "John", "Age" -> "30", "Country" -> "USA"),
Map("Name" -> "Anna", "Age" -> "28", "Country" -> "UK")
)
val headers = data.head.keys.toSeq
val rows = data.map(_.values.toSeq)
writer.writeRow(headers)
writer.writeAll(rows)
writer.close()
}
}
Output:
Reading CSV in Scala
We will use the scala-csv library to read data from a CSV file and print it to the console. The data will be read as a list of maps where each map represents a row with column headers as keys.
Approach:
- Import the necessary libraries.
- Open the CSV file using CSVReader.
- Read all rows with headers using allWithHeaders().
- Print each row.
- Close the reader.
Below is the Scala program to read a CSV file:
import java.io.File
import com.github.tototoshi.csv._
object ReaderExample2 {
def main(args: Array[String]): Unit = {
val reader = CSVReader.open(new File("output.csv"))
val allRows = reader.allWithHeaders()
allRows.foreach(println)
reader.close()
}
}
Output:
How to Read and Write CSV File in Scala?
Data processing and analysis in Scala mostly require dealing with CSV (Comma Separated Values) files. CSV is a simple file format used to store tabular data, such as a spreadsheet or database. Each line of a CSV file is plain text, representing a data row, with values separated by commas (,). Reading from and writing to CSV files are common tasks across several programming situations. This article focuses on discussing steps to read and write CSV files in Scala.
Table of Content
- Setting Up the Environment
- Using Java.io.PrintWriter Class
- Using Scala-csv Library
- Conclusion
- FAQs