【问题标题】:Export JSON Data to CSV File in AngularJs based on ui-grid's every row id根据 ui-grid 的每一行 id 将 JSON 数据导出到 AngularJs 中的 CSV 文件
【发布时间】:2020-05-03 05:05:41
【问题描述】:

在 AngularJs 中根据 ui-grid 的每一行 id 将 JSON 数据导出到 CSV 文件

我需要 angularjs 1.0 UI-grid 的每一行中的 CSV 导出选项,用户将在其中单击该按钮,并且基于 id 服务器将响应基于 JSON 的数据,然后它应该以 CSV 格式下载。

使用导出 CSV 按钮查看下图。

这是我迄今为止尝试过的:

网格的列定义

         {
             field: "actions", "name": "Action",
             cellTemplate: '<button type="button" field-separator=","  ng-click="funcExport({{row.entity._id}})" csv-header="exportHeader" ng-csv="export" filename="Sample.csv">Export CSV</button>',
             width: "170"
         }

导出函数到 CSV:目前 JSON 数据不是基于 id 而是静态的用于演示。

    /*Function to export*/
var funcExport = function (id) {
    $scope.exportarray = [];
    $scope.exportHeader = [];
    $scope.export = [];
    $scope.exportHeader = ['Licence', 'Condition'];

    $scope.exportarray = [{ "Licence": "229973", "Condition": "Usage" }, { "Licence": "24141", "Condition": "Level" }];

    $scope.export = $scope.exportarray;
}

任何帮助将不胜感激!

【问题讨论】:

    标签: javascript angularjs export-to-csv


    【解决方案1】:

    首先将 JSON 转换为逗号分隔的 CSV 字符串,然后创建一个锚标记 (a) 将此 CSV 字符串设置为 href 触发点击,删除锚标记。

    function convertToCSV(array) {
    
        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;
    }
    
    function exportCSVFile(headers, items, fileTitle) {
    
        items.unshift(headers);
    
        var csv = convertToCSV(items);
        var exportedFilenmae = fileTitle + '.csv' || 'export.csv';
    
        var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
        if (navigator.msSaveBlob) { // IE 10+
            navigator.msSaveBlob(blob, exportedFilenmae);
        } else {
            var link = document.createElement("a");
            if (link.download !== undefined) { // feature detection
                // Browsers that support HTML5 download attribute
                var url = URL.createObjectURL(blob);
                link.setAttribute("href", url);
                link.setAttribute("download", exportedFilenmae);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        }
    }
    
    /*Function to export*/
    var funcExport = function (id) {
    
        var exportHeader = ['Licence', 'Condition'];
    
        var exportarray = [{ "Licence": "229973", "Condition": "Usage" }, { "Licence": "24141", "Condition": "Level" }];
    
        exportCSVFile(exportHeader , exportarray, 'download' );
    
    }
    

    此代码取自here

    【讨论】:

    • exportCSVFile 方法中未定义的 jsonObject,convertToCSV 方法中缺少 objArray 的解析,exportCSVFile 方法中缺少 fileTitle 参数。但是,我围绕您的参考工作,这就像一个魅力!谢谢!!
    • 对不起,我复制了这些代码并尝试清理并且没有运行发布在这里。这导致了这些错误。我已经更新了我的代码。不客气。
    【解决方案2】:

    这是一个可行的解决方案

    将 Javascript 对象数组转换为 CSV

    function convertToCSV(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;
    }
    

    导出为 CSV 函数

    function exportCSVFile(headers, items, fileTitle) {
         if (headers) {
            items.unshift(headers);
        }
        // Convert Object to JSON
        var jsonObject = JSON.stringify(items);
    
        var csv = convertToCSV(jsonObject);
        var exportedFilenmae = fileTitle + '.csv' || 'wal_export.csv';
    
        var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
        if (navigator.msSaveBlob) { // IE 10+
            navigator.msSaveBlob(blob, exportedFilenmae);
        } else {
            var link = document.createElement("a");
            if (link.download !== undefined) { // feature detection
                // Browsers that support HTML5 download attribute
                var url = URL.createObjectURL(blob);
                link.setAttribute("href", url);
                link.setAttribute("download", exportedFilenmae);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        }
    }
    

    要在 ui-grid 行中调用的函数

    $scope.funcExport = function (row) {
            var id = row.entity._id;//this will be used for dynamic data later
            var exportHeader = ['Licence', 'Condition'];
            var headers = {
                licence: 'Licence'.replace(/,/g, ''), // remove commas to avoid errors
                condition: "Condition"
            };
            var exportarray = [
                                { "licence": "229973", "condition": "Usage" }, 
                                { "licence": "24141", "condition": "Level" }
                              ];
    
            var fileTitle = 'WAL_CSV'; // or 'my-unique-title'
            exportCSVFile(headers, exportarray, fileTitle);
    
        }
    

    最后是ui-grid的列定义

    {
       field: "actions", "name": "Action",                 
       cellTemplate: '<a ng-click="grid.appScope.funcExport(row)"> Download {{row.entity.LicenceType}} CSV </a>',                
       width: "170"
     }
    

    解决方案是基于Danny PuleExport JSON to CSV file using Javascript (in the browser).

    【讨论】:

      猜你喜欢
      • 2020-10-04
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      相关资源
      最近更新 更多