Skip to content
Snippets Groups Projects
Commit 31318314 authored by Lorenz Boguhn's avatar Lorenz Boguhn Committed by Sören Henning
Browse files

Csv export: Add commas to the column names

Add method addQuotationMarks to IOHandler.kt
Adapt the associated test
parent cb0724c7
No related branches found
No related tags found
1 merge request!289Fix Csv export
......@@ -71,21 +71,32 @@ class IOHandler {
fun writeToCSVFile(fileURL: String, data: List<List<String>>, columns: List<String>) {
val outputFile = File("$fileURL.csv")
PrintWriter(outputFile).use { pw ->
pw.println(columns.joinToString(separator = ","))
val writeColumns = addQuotationMarks(columns)
pw.println(writeColumns.joinToString(separator = ","))
data.forEach{ row ->
val writeRow = row.toMutableList()
// change entry if it contains a comma
writeRow.forEachIndexed { index, entry ->
if (entry.contains(",")){
writeRow[index] = "\"" + entry + "\""
}
}
val writeRow = addQuotationMarks(row)
pw.println(writeRow.joinToString(separator = ","))
}
}
logger.info { "Wrote CSV file: $fileURL to ${outputFile.absolutePath}." }
}
/**
* For a list of Strings:
* Adds quotation marks around strings that contain a comma
*/
private fun addQuotationMarks(stringList: List<String> ): List<String> {
val stringMutableList = stringList.toMutableList()
stringMutableList.forEachIndexed { index, entry ->
if (entry.contains(",")){
stringMutableList[index] = "\"" + entry + "\""
}
}
return stringMutableList
}
/**
* Write to text file
*
......
......@@ -43,12 +43,13 @@ internal class IOHandlerTest {
temporaryFolder.create()
val folder = temporaryFolder.newFolder(FOLDER_URL)
val columns = listOf("Fruit", "Color")
val testContent = listOf(
listOf("apples", "red"),
listOf("bananas", "yellow"),
listOf("avocado", "brown")
)
val columns = listOf("Fruit", "Color")
IOHandler().writeToCSVFile(
fileURL = "${folder.absolutePath}/test-file",
......@@ -74,7 +75,8 @@ internal class IOHandlerTest {
temporaryFolder.create()
val folder = temporaryFolder.newFolder(FOLDER_URL)
val columns = listOf("Fruit", "Color")
val columns = listOf("Fruit, Fruit2", "Color")
val expectedColumns = listOf("\"Fruit, Fruit2\"", "Color")
val testContent = listOf(
listOf("apples, paprika", "red"),
......@@ -95,7 +97,7 @@ internal class IOHandlerTest {
)
// construct string from the columns
var expected = columns.stream().collect(Collectors.joining(","))
var expected = expectedColumns.stream().collect(Collectors.joining(","))
// add values from the expectedContent to expected string
expectedContent.forEach{
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment