I’ve just spent a few hours trying to work out exactly how I can convert a JSON array into a CSV file which the user can save to their phone. The use case for this scenario is as follows:
User opens App
App displays results from a noSQL database as an ion-list
User wishes to save this data as a CSV, thereofre clicks the “Download to CSV” button
App generates CSV file and saves it in the “Downloads” directory of the phone
I assumed this would be a reasonably common scenario, however I have been unable to find any sample code online. I’ve searched the Ionic forums and found a few people asking the same question for Ionic 1, but none of these had solid answers and it didn’t seem like anyone else has asked the question for Ionic 2.
I managed to write a javascript function to convert a JSON object to a CSV file, however this only works in my browser (Chrome) and not on my Android device.
Do I need to use Native plugins like the File Plugin? I’m finding the documentation there a bit ‘thin’ to follow.
Does anyone have a working example of the functionality I require?
Unfortunately not, I ended up abandoning the idea as I didn’t receive any response from the community and I couldn’t solve the problem myself. I would still love to know the answer
convertToCSV(teams) {
var csv: any = ''
var line: any = ''
var SpT = teams[0].length
var anzahlTeams = teams.length
//Header
for (var i = 0; i < anzahlTeams; i++) {
if (line != '') line += ';'
line += "Team " + (i + 1)
}
csv += line + '\r\n';
//Teams
for (var i = 0; i < SpT; i++) {
line = ''
for (var j = 0; j < anzahlTeams; j++) {
if (line != '') line += ';'
line += teams[j][i]
}
csv += line + '\r\n'
}
return csv
}
Thanks for the tutorial! It works fine with the local file.
In the next step I wanted to fetch a local file from the android system with the filechooser plugin. I’m getting the uri from the file-chooser plugin, which I load instead of the local file path of the tutorial. Unfortunately the script throws an error when loading the file.
as of new native coding convention, you need to add file to the constructor and then use code like below. Next, the externalRootDirectory is android only, so I replaced with dataDirectory.
Got this working on Android. Won’t work on Ionic View Pro (file plugin not supported).
Next adventure for me: find the file and put it in a socialshare (or email composer).