How to create a csv file from a JSON array

Hi guys,
I am looking for a solution to create a csv (or excel) file from a Json array (on the fly).

Do I need to use a temporary file (with the default cordova plugin for instance) and then, make it downloadable from my button ?

I tried to include it automatically to a mail (with the default cordova mail plugin). But every time the file created was invalid…

Do you know how can I do it ?

Cheers !

Hi, I have never tried on ionic. But with javascript you can do it with Blob :

var data = new Blob([text], {type: ‘text/csv’});

// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
var link = document.createElement(“a”);
link.setAttribute(“href”, textFile);
link.setAttribute(“download”, “csv.csv”);

And for the “text”, for each line you can do line + " \n "

Hi,
Thank you for your answer.
I tried your solution. I can’t say It doesn’t work because my button doesn’t trigger anything.

This is my formula :

<ion-item ng-click="onSelectExport()">
          <i class="current-value">CSV Export</i>
</ion-item>

Do you know what should I do to make this csv object downloadable ??

the $scope.onSelectExport function should trigger something. do you have errors ?

No I don’t actually. It’s working now…

And in order to export my Json object to a csv file, I did this :

$scope.Export = app.onSelectExport();

$scope.onSelectExport = function() {
    cordova.plugins.email.open({
        to:      '',
        cc:      '',
        bcc:     '',
        subject: 'Date export '+ $scope.Date.date,
        body:    '',
        attachments: 'base64:export.csv//'+btoa($scope.Export)
    });

And I use this function to create the csv file :

      var ConvertToCSV = function(objArray) {
        var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
        var str = '';

        for (var i = 0; i < array.length; i++) {
            var line = '';
        for (var index in array[i]) {
            if (line != '') line += ','

            line += array[i][index];
        }

        str += line + '\r\n';
    }
    return str;
};

This is working fine. I don’t need to download the file anymore…
The users will manage to send their own export to their email…

Problem solved.
Thank you very much for you time

How to make ngCSV work on ionic ? that when done generating the data it will be downloaded?

Can you please explain this? Whether first should call “ConvertToCSV” & then call “onSelectExport” ? what is the input for “ConvertToCSV” , where have you used the return value of it?