Add csv export
parent
eb764277dd
commit
a09b749133
|
@ -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)
|
||||
|
||||
|
|
Loading…
Reference in New Issue