【问题标题】:How to convert a json object into .csv file and how to export using Ionic 2 + angular 2?如何将 json 对象转换为 .csv 文件以及如何使用 Ionic 2 + angular 2 导出?
【发布时间】:2017-07-04 05:38:23
【问题描述】:

我在 Angular 2 应用程序中使用一个函数将 JSON 数据转换并导出为 .CSV。以下是我的功能,在 angular 2 应用程序中运行良好 (网络)。我尝试在使用 Ionic 2 开发的移动应用程序中使用的相同,它在移动应用程序中不起作用。有没有办法做到这一点?

谢谢!

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;
    }

【问题讨论】:

标签: json csv ionic2


【解决方案1】:

在 Ionic 2 中使用“cordova-plugin-file”导出 csv。

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

如果您看到以下错误 -

代码:1 消息:“NOT_FOUND_ERR”

在 config.xml 中添加以下行之一来解决它。

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

如插件文档中所述,您可以使用这两个选项之一:

选择是否在内部存储文件 文件存储位置,或者使用前面的逻辑,有偏好 在应用程序的 config.xml 文件中。如果没有这一行,文件插件将使用 Internal 作为 默认。如果存在偏好标签,并且不是这些标签之一 值,应用程序将不会启动。

如果您的应用程序之前已交付给用户,请使用 此插件的旧(3.0.0 之前)版本,并已将文件存储在 持久文件系统,那么您应该将首选项设置为 如果您的 config.xml 没有为 持久文件系统。将位置切换到“内部”意味着 升级其应用程序的现有用户可能无法 访问他们以前存储的文件,具体取决于他们的设备。

如果您的应用程序是新的,或者以前从未在 持久文件系统,那么内部设置通常是 推荐。

【讨论】:

    猜你喜欢
    • 2017-01-03
    • 1970-01-01
    • 2018-12-10
    • 2016-11-17
    • 2017-09-29
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 2017-03-20
    相关资源
    最近更新 更多