From a09b74913380f91c478fdd2bf572ab08eb2eda04 Mon Sep 17 00:00:00 2001 From: CAPEL Maxime <83071634+fortyup@users.noreply.github.com> Date: Tue, 5 Dec 2023 14:07:53 +0100 Subject: [PATCH] Add csv export --- src/main/kotlin/main/Main.kt | 66 +++++++++++++++++++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/src/main/kotlin/main/Main.kt b/src/main/kotlin/main/Main.kt index 2ae0630..f6f84c6 100644 --- a/src/main/kotlin/main/Main.kt +++ b/src/main/kotlin/main/Main.kt @@ -27,6 +27,9 @@ import kotlinx.serialization.json.put import java.io.File import java.io.FileWriter import java.io.IOException +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive val connection = DatabaseManager.getConnection() @@ -120,7 +123,24 @@ fun App() { println("Open command cancelled by user.") } }, - onExporterClick = { /* Action d'export */ }, + onExporterClick = { + val fileDialog = FileDialog(Frame(), "Save as", FileDialog.SAVE) + fileDialog.file = "GlossaireExporte.csv" + fileDialog.isVisible = true + + val selectedFile = fileDialog.file + val selectedDirectory = fileDialog.directory + + if (selectedFile != null) { + val csvFilePath = selectedDirectory + selectedFile + println("Exporting to: $csvFilePath") + + exportJsonToCSV("glossaire.json", csvFilePath) + } else { + println("Export command cancelled by user.") + } + } + , onRetourClick = { currentPage.value = "accueil" } ) } @@ -188,6 +208,50 @@ fun App() { } } +fun exportJsonToCSV(jsonFilePath: String, csvFilePath: String) { + try { + // Read JSON file + val jsonContent = File(jsonFilePath).readText(Charsets.UTF_8) + val glossaryData = Json.parseToJsonElement(jsonContent) + + if (glossaryData is JsonObject) { + val header = glossaryData.keys.toList() + val csvContent = buildString { + // Append the header + append(header.joinToString(separator = ";")) + append("\n") + + // Append the data + appendJsonToCSV(glossaryData, this) + } + + // Write to CSV file + File(csvFilePath).writeText(csvContent, Charsets.UTF_8) + println("Export successful. File saved at: $csvFilePath") + } else { + println("Invalid JSON file format.") + } + } catch (e: IOException) { + println("Error exporting data: ${e.message}") + } +} + +fun appendJsonToCSV(json: JsonObject, stringBuilder: StringBuilder) { + val values = json.values.map { + when (it) { + is JsonPrimitive -> it.content + is JsonObject -> { + val nestedValues = buildString { appendJsonToCSV(it, this) } + "\"$nestedValues\"" + } + else -> "" + } + } + + stringBuilder.append(values.joinToString(separator = ";")) + stringBuilder.append("\n") +} + fun importCSV(cheminFichier: String) { val file = File(cheminFichier).readText(Charsets.UTF_8)