How to convert json object to CSV file and how to export using Ionic 2 + angular 2?

I use a function in my angular 2 application to convert and export JSON data to .CSV. Below is my function and it works fine in angular 2 (web) application. I tried to use the same thing in a mobile application that I developed using Ionic 2, it does not work in a mobile application. Is there any way to do this?

Thank!

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;
    }
+4
source share
1 answer

Use "cordova-plugin-file" to export csv to Ionic 2.

https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/

If you see the following error -

code: 1 : "NOT_FOUND_ERR"

config.xml, .

<preference name="AndroidPersistentFileLocation" value="Internal" />
<preference name="AndroidPersistentFileLocation" value="Compatibility" />

, :

, , config.xml. File Internal . , .

, ( 3.0.0) , , config.xml . "" , , , .

, .

+2

Source: https://habr.com/ru/post/1680683/


All Articles