How to convert a json object into .csv file and how to export using Ionic 2 + angular 2?

Viewed 3496

I'm using a function in my angular 2 application to convert and export a JSON data into .CSV. The below is my function and is working fine in angular 2 application (web). The Same I tried to use in mobile app which I developed using Ionic 2, it is not working in mobile app. Is there any way to do this?

Thanks!

saveAsCSV() {
       let sampleJson : any = [{name:'ganesh', age:'24'},{name:'ramesh', age:'24'},{name:'suresh', age:'24'}]
       this.saveData = [];    
       let a = document.createElement("a");    
        a.setAttribute('style', 'display:none;');    
        document.body.appendChild(a);    
       let csvData = ConvertToCSV(sampleJson);    
       let blob = new Blob([csvData], { type: 'text/csv' });    
       let url= window.URL.createObjectURL(blob);    
        a.href = url;    
        a.download = 'sample.csv'; 
        a.click();    
  }

ConvertToCSV(objArray) {    
        let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
        let str = '';
        let row = ""; 
        for (let index in objArray[0]) {
            //Now convert each value to string and comma-separated
            row += index + ',';
        }
        row = row.slice(0, -1);
        //append Label row with line break
        str += row + '\r\n';

        for (let i = 0; i < array.length; i++) {
            let line = '';
            for (let index in array[i]) {
                if (line != '') line += ',';
                line += array[i][index];
            }
            str += line + '\r\n';
        }
        return str;
    }
1 Answers
Related