I want to write ByteArray data which is coming from Retrofit API (ResponseBody as return type from API) into Excel file and store into external memory of android SD Card.
try {
var path = mContext?.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
val stream = FileOutputStream(path.toString() + "/ExcelTest.xlsx")
stream.write(it.data?.bytes())//it.data->retrofit ResponseBody that am convert to ByteArray
stream.flush()
stream.close()
//To open the Excel file
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(
Uri.fromFile(path),
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
}
mContext?.startActivity(intent)
} catch (e: FileNotFoundException) {
}
This is my suspend function:
@GET("URL")
@Streaming
suspend fun getDownloadFile(): ResponseBody
Output:
When I run the app, its creating Excel file with empty data(0KB) in it. and when I tried opened the created file its showing this popup alert:
Excel cannot open the file ’ExcelTest.xlsx’ because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.
Ajay gadadasu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
0