简体   繁体   English

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

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

Export JSON Data to CSV File in AngularJs based on ui-grid's every row id根据 ui-grid 的每行 id 将 JSON 数据导出到 AngularJs 中的 CSV 文件

I need a CSV export option in angularjs 1.0 UI-grid's every row, where the user will click on that button, and based on the id server will respond a JSON based data then it should download in CSV format. I need a CSV export option in angularjs 1.0 UI-grid's every row, where the user will click on that button, and based on the id server will respond a JSON based data then it should download in CSV format.

See the below image with Export CSV button.使用导出 CSV按钮查看下图。

在此处输入图像描述

Here's what I have tried so far:这是我到目前为止所尝试的:

Grid's column Definition网格的列定义

         {
             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 : Currently JSON data is not based on id but in static for demonstration.导出 Function 到 CSV :目前 JSON 数据不是基于 id 而是基于 ZA81259CEF8E959C297EDF1 的演示。

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

Any help would be appreciated!!任何帮助,将不胜感激!!

First convert JSON to comma separated CSV string then crate an anchor tag(a) set this CSV string as href fire a click, remove anchor tag.首先将 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' );

}

This code was taken from here这段代码取自这里

Here's a working solution这是一个有效的解决方案

convert a Javascript array of object to CSV将 object 的 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;
}

Export to CSV Function导出到 CSV Function

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

Function to be called in a ui-grid row Function 在 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);

    }

Finally, ui-grid's column definition最后,ui-grid的列定义

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

The solution is based on Danny Pule Export JSON to CSV file using Javascript (in the browser).该解决方案基于Danny Pule使用 Javascript(在浏览器中)将 JSON 导出到 CSV 文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM