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]) {
row += index + ',';
}
row = row.slice(0, -1);
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;
}
source
share