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

Export JSON Data to CSV File in AngularJs based on ui-grid's every row id

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

我需要在 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"
         }

Export Function To 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;
}

如有任何帮助,我们将不胜感激!

首先将 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

这是一个可行的解决方案

将 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- 网格行中调用的函数

$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 Pule 使用 Javascript 将 JSON 导出到 CSV 文件(在浏览器中)。