Check this post - https://www.baeldung.com/kotlin/csv-files - it contains a few nice references to some libraries or pure Kotlin approaches if you prefer to use those.
Applying it to your use case, maybe something like:
fun OutputStream.writeCsv(context: Context, listOfData: List<YourData>) {
//get data create directory
......
val writer = bufferedWriter()
writer.write(""""Name", "Address", "Code"""")
writer.newLine()
listOfData.forEach {
writer.write("${it.name}, ${it.address}, \"${it.code}\"")
writer.newLine()
}
writer.flush()
writer.close()
}
And then call this where you need it,
FileOutputStream("out777.cs").apply { writeCsv(listOfData) }
One thing to note here is using bufferedWriter:
FileWriter writes directly into Files and should be used only when the number of writes is less. BufferedWriter: BufferedWriter is almost similar to FileWriter but it uses internal buffer to write data into File. So if the number of write operations is more, the actual IO operations are less and performance is better.
Not tested but this might point you in a more cleaner and efficient solution. There are also some libraries specifically for this. Take a look
Answer from moondev on Stack OverflowVideos
After writing to the file you must close it:
fileWriter.close()
and make this change: sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(qponFile))
val HEADER = "Name, DateTime"
var filename = "export.csv"
var path = getExternalFilesDir(null) //get file directory for this package
//(Android/data/.../files | ... is your app package)
//create fileOut object
var fileOut = File(path, filename)
//delete any file object with path and filename that already exists
fileOut.delete()
//create a new file
fileOut.createNewFile()
//append the header and a newline
fileOut.appendText(HEADER)
fileOut.appendText("\n")
// trying to append some data into csv file
fileOut.appendText("Haider, 12/01/2021")
fileOut.appendText("\n")
val sendIntent = Intent(Intent.ACTION_SEND)
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(fileOut))
sendIntent.type = "text/csv"
startActivity(Intent.createChooser(sendIntent, "SHARE"))