From 7047e3460edcedbcdd4e8fc37dd0b8b9b81a4f7e Mon Sep 17 00:00:00 2001 From: CAPEL Maxime <83071634+fortyup@users.noreply.github.com> Date: Wed, 6 Dec 2023 09:14:57 +0100 Subject: [PATCH] Re-add export to csv --- src/main/kotlin/main/Main.kt | 46 +++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/src/main/kotlin/main/Main.kt b/src/main/kotlin/main/Main.kt index 2ae0630..aaa1b53 100644 --- a/src/main/kotlin/main/Main.kt +++ b/src/main/kotlin/main/Main.kt @@ -22,6 +22,7 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.window.* import database.DatabaseManager +import kotlinx.serialization.json.Json import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put import java.io.File @@ -120,7 +121,21 @@ fun App() { println("Open command cancelled by user.") } }, - onExporterClick = { /* Action d'export */ }, + onExporterClick = { + val fileDialog = FileDialog(Frame(), "Save as CSV", FileDialog.SAVE) + fileDialog.file = "glossaire_exporte.csv" // Initial file name + fileDialog.isVisible = true + val selectedFile = fileDialog.file + val selectedDirectory = fileDialog.directory + if (selectedFile != null) { + val csvFilePath = "$selectedDirectory$selectedFile" + val jsonFilePath = "glossaire.json" // Replace with the actual path to your JSON file + println("Exporting to: $csvFilePath") + exportToCSV(jsonFilePath, csvFilePath) + } else { + println("Export command cancelled by user.") + } + }, onRetourClick = { currentPage.value = "accueil" } ) } @@ -188,6 +203,35 @@ fun App() { } } +fun exportToCSV(jsonFilePath: String, csvFilePath: String) { + val glossary = readJsonFile(jsonFilePath) + val csvContent = buildString { + appendLine("nom,description,contextePrincipal,contexte2,lieA,synonyme,antonyme") + glossary.forEach { entry -> + appendLine( + "${entry["nom"]},${entry["description"]},${entry["contextePrincipal"]}," + + "${entry["contexte2"]},${entry["lieA"]},${entry["synonyme"]},${entry["antonyme"]}" + ) + } + } + try { + FileWriter(csvFilePath).use { fileWriter -> + fileWriter.write(csvContent) + } + } catch (e: IOException) { + e.printStackTrace() + } +} +fun readJsonFile(filePath: String): List> { + return try { + val content = File(filePath).readText(Charsets.UTF_8) + Json.decodeFromString(content) + } catch (e: Exception) { + e.printStackTrace() + emptyList() + } +} + fun importCSV(cheminFichier: String) { val file = File(cheminFichier).readText(Charsets.UTF_8)