在Angular中将JSON导出为CSV

时间:2015-08-12 15:22:55

标签: json angularjs csv

我正在寻找使用Angular将JSON对象转换为CSV格式的方法。我遇到了这个https://www.npmjs.com/package/jsonexport,这正是我想要使用的东西,但我不确定我是否可以在Angular中实际使用它(似乎特定于节点?),如果没有,是否有任何现成的指令在那里,我可以提供一些JSON来获取CSV。

任何人都可以指出一些有用的例子,我已经浏览了一下,它们似乎很少,而且我发现它们似乎只能处理非常基本的平面JSON结构。

由于

4 个答案:

答案 0 :(得分:3)

试试这个http://ngmodules.org/modules/ng-csv

对于工作示例 - https://asafdav.github.io/ng-csv/example/

用法示例js(取自他们的文档)

<强>脚本

    var myapp = angular.module('myapp', ["ngSanitize", "ngCsv"]);

    myapp.controller('myctrl', function ($scope) {
        $scope.filename = "test";
        $scope.getArray = [{a: 1, b:2}, {a:3, b:4}];

      $scope.addRandomRow = function() {
        $scope.getArray.push({a: Math.floor((Math.random()*10)+1), b: Math.floor((Math.random()*10)+1)});
      };

      $scope.getHeader = function () {return ["A", "B"]};

      $scope.clickFn = function() {
        console.log("click click click");
      };
    });

<强>标记

<div ng-app="myapp">
    <div class="container" ng-controller="myctrl">

      <div class="page-header">
        <h1>ngCsv <small>example</small></h1>
      </div>

      <div class="form-group">
        <label for="filename">Filename </label>
        <input type="text" id="filename" class="form-control" ng-model="filename">
      </div>

      <div class="form-group">
        <label for="separator">Field separator</label>
        <input type="text" id="separator" class="form-control" ng-model="separator" ng-init="separator=','">
      </div>

      <div class="form-group">
        <label for="decimal-separator">Decimal separator</label>
        <input type="text" id="decimal-separator" class="form-control" ng-model="decimalSeparator" ng-init="decimalSeparator='.'">
      </div>            

      <button class="btn btn-default"
              ng-csv="getArray" filename="{{ filename }}.csv" field-separator="{{separator}}" decimal-separator="{{decimalSeparator}}"
              >Export to CSV</button>

      <button class="btn btn-default"
              ng-csv="getArray" csv-header="getHeader()" filename="{{ filename }}" field-separator="{{separator}}" decimal-separator="{{decimalSeparator}}"
              >Export to CSV with header</button>

      <button class="btn btn-default"
              ng-csv="getArray" csv-header="getHeader()" filename="{{ filename }}" field-separator="{{separator}}" decimal-separator="{{decimalSeparator}}"
              ng-click="clickFn()">Export with ng-click</button>

      <button class="btn btn-default"
              ng-csv="getArray" filename="{{ filename }}.csv" field-separator="{{separator}}" decimal-separator="{{decimalSeparator}}" add-bom="true"
        >With BOM</button>

      <button class="btn btn-default" ng-click="addRandomRow()">Add row</button>
    </div>
</div>

答案 1 :(得分:1)

您可以使用此简单代码从JSON导出为CSV。此代码解决了许多基本问题,例如分隔符问题,自定义标题,跳过空列并添加-代替特定列的空数据。请参阅此github链接来解决有关Angular中CSV导出的所有问题。

https://github.com/marvin-aroza/Angular-csv-export

将其作为JSON数据考虑

jsonData : any = [{
    name : 'Berlin',
    age : '45',
    country : 'Spain',
    phone : '896514326'
  },
  {
    name : 'Professor',
    age : '42',
    country : 'spain'
  },
  {
    name : 'Tokyo',
    age : '35',
    phone : '854668244'
  },
  {
    name : 'Helsinki',
    phone : '35863297'
  }];

您可以使用这些功能下载csv

exportCsv() {
    this.downloadFile(this.jsonData);
  }

  downloadFile(data, filename = 'data') {
    let arrHeader = ["name", "age", "country", "phone"];
    let csvData = this.ConvertToCSV(data, arrHeader);
    console.log(csvData)
    let blob = new Blob(['\ufeff' + csvData], { type: 'text/csv;charset=utf-8;' });
    let dwldLink = document.createElement("a");
    let url = URL.createObjectURL(blob);
    let isSafariBrowser = navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1;
    if (isSafariBrowser) {  //if Safari open in new window to save file with random filename.
      dwldLink.setAttribute("target", "_blank");
    }
    dwldLink.setAttribute("href", url);
    dwldLink.setAttribute("download", "sample.csv");
    dwldLink.style.visibility = "hidden";
    document.body.appendChild(dwldLink);
    dwldLink.click();
    document.body.removeChild(dwldLink);
  }

要编辑CSV格式,您可以添加此功能

ConvertToCSV(objArray, headerList) {
    console.log(objArray);
    console.log(headerList);
    let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    let str = '';
    let row = 'S.No,';

    let newHeaders = ["Name", "Age", "Country", "Phone"];

    for (let index in newHeaders) {
      row += newHeaders[index] + ',';
    }
    row = row.slice(0, -1);
    str += row + '\r\n';
    for (let i = 0; i < array.length; i++) {
      let line = (i + 1) + '';
      for (let index in headerList) {
        let head = headerList[index];

        line += ',' + this.strRep(array[i][head]);
      }
      str += line + '\r\n';
    }
    return str;
  }

如果值带有逗号,则可以使用此功能删除逗号并将其视为一个值

strRep(data) {
    if(typeof data == "string") {
      let newData = data.replace(/,/g, " ");
       return newData;
    }
    else if(typeof data == "undefined") {
      return "-";
    }
    else if(typeof data == "number") {
      return  data.toString();
    }
    else {
      return data;
    }
  }

答案 2 :(得分:0)

 没有选项可以在ui-grid中导出子网格数据。但我们有另一种选择,使用FileSaver.js将ui-grid和它的子网格数据导出为.csv文件。我创建了一个指令来获取网格数据/ Json数据,然后像树结构一样格式化数据,然后使用FileSaver.js下载.csv文件。它有一个嵌套网格的限制。

    angular.module("exampleModule", [])
.controller('exampleController', function ($scope) {
                $scope.dataList = [
                    {
                        id: 1,
                        name: 'github',
                        price: '200$',
                        publisher: {
                            name: 'hieutran',
                            company: 'Dtag-VN'
                        },
                        nested:[
                         {
                            name: 'name1',
                            company: 'company1'
                        },
                        {
                            name: 'name2',
                            company: 'company2'
                        }]
                    },
                     {
                        id: 2,
                        name: 'twitter',
                        price: '500$',
                        publisher: {
                            name: 'twitter tran',
                            company: 'Canada'
                        },
                         nested:[]
                    },

                    {
                        id: 3,
                        name: 'google',
                        price: '300$',
                        publisher: {
                            name: 'tran',
                            company: 'Vietname'
                        },
                         nested:[
                         {
                            name: 'name3',
                            company: 'company3'
                        },
                        {
                            name: 'name4',
                            company: 'company4'
                        }]
                    }
                ]
            })
                            .directive("ngGridJsonExportExcel", function($timeout) {
                                return {
                                    restrict: "AE",
                                    scope: {
                                        data: "=",
                                        filename: "=?",
                                        reportFields: "=",
                                        nestedReportFields: "=",
                                        nestedDataProperty: "@"
                                    },
                                    link: function(scope, element) {
                                        scope.filename = !!scope.filename ? scope.filename : "export-excel";

                                        function generateFieldsAndHeaders(fieldsObject, fields, header) {
                                            _.forEach(fieldsObject, function(field, key) {
                                                if (!field || !key) {
                                                    throw new Error("error json report fields");
                                                }
                                                fields.push(key);
                                                header.push(field);
                                            });
                                            return {fields: fields, header: header};
                                        }
                                        var fieldsAndHeader = generateFieldsAndHeaders(scope.reportFields, [], []);
                                        var fields = fieldsAndHeader.fields, header = fieldsAndHeader.header;
                                        var nestedFieldsAndHeader = generateFieldsAndHeaders(scope.nestedReportFields, [], [""]);
                                        var nestedFields = nestedFieldsAndHeader.fields, nestedHeader = nestedFieldsAndHeader.header;
                                        function _convertToExcel(body, header) {
                                            return header + "\n" + body;
                                        }
                                        function _objectToString(object) {
                                            var output = "";
                                            _.forEach(object, function(value, key) {
                                                output += key + ":" + value + " ";
                                            });

                                            return "'" + output + "'";
                                        }
                                        function generateFieldValues(list, rowItems, dataItem) {
                                            _.forEach(list, function(field) {
                                                var data = "", fieldValue = "", curItem = null;
                                                if (field.indexOf(".")) {
                                                    field = field.split(".");
                                                    curItem = dataItem;
                                                    // deep access to obect property
                                                    _.forEach(field, function(prop) {
                                                        if (curItem !== null && curItem !== undefined) {
                                                            curItem = curItem[prop];
                                                        }
                                                    });
                                                    data = curItem;
                                                } else {
                                                    data = dataItem[field];
                                                }
                                                fieldValue = data !== null ? data : " ";
                                                if (fieldValue !== undefined && angular.isObject(fieldValue)) {
                                                    fieldValue = _objectToString(fieldValue);
                                                }
                                                rowItems.push(fieldValue);
                                            });
                                            return rowItems;
                                        }
                                        function _bodyData() {
                                            var body = "";

                                            _.forEach(scope.data, function(dataItem) {
                                                var rowItems = [];var nestedBody = "";
                                                rowItems = generateFieldValues(fields, rowItems, dataItem);
                                                //Nested Json body generation start 
                                                if (scope.nestedDataProperty && dataItem[scope.nestedDataProperty].length) {
                                                    _.forEach(dataItem[scope.nestedDataProperty], function(nestedDataItem) {
                                                        var nestedRowItems = [""];
                                                        nestedRowItems = generateFieldValues(nestedFields, nestedRowItems, nestedDataItem);
                                                        nestedBody += nestedRowItems.toString() + "\n";
                                                    });
                                                    var strData = _convertToExcel(nestedBody, nestedHeader);
                                                    body += rowItems.toString() + "\n" + strData;
                                                    ////Nested Json body generation end 
                                                } else {
                                                    body += rowItems.toString() + "\n";
                                                }
                                            });
                                            return body;
                                        }

                                        $timeout(function() {
                                            element.bind("click", function() {
                                                var bodyData = _bodyData();
                                                var strData = _convertToExcel(bodyData, header);
                                                var blob = new Blob([strData], {
                                                    type: "text/plain;charset=utf-8"
                                                });

                                                return saveAs(blob, [scope.filename + ".csv"]);
                                            });
                                        }, 1000);
                                    }
                                };
                            });

HTML code:

<button ng-json-export-excel data="dataList"  nested-data-property="nested" report-fields="{id: 'ID Heder', name: 'Name Header', price: 'Price Head',  'publisher.name': 'Publisher Head', 'publisher.company': 'Company Head'}" nested-report-fields="{name: 'Nested Name', company: 'Nested Company'}">Json Export</button>

Here is my plunker

angular.module("exampleModule", []) .controller('exampleController', function ($scope) { $scope.dataList = [ { id: 1, name: 'github', price: '200$', publisher: { name: 'hieutran', company: 'Dtag-VN' }, nested:[ { name: 'name1', company: 'company1' }, { name: 'name2', company: 'company2' }] }, { id: 2, name: 'twitter', price: '500$', publisher: { name: 'twitter tran', company: 'Canada' }, nested:[] }, { id: 3, name: 'google', price: '300$', publisher: { name: 'tran', company: 'Vietname' }, nested:[ { name: 'name3', company: 'company3' }, { name: 'name4', company: 'company4' }] } ] }) .directive("ngGridJsonExportExcel", function($timeout) { return { restrict: "AE", scope: { data: "=", filename: "=?", reportFields: "=", nestedReportFields: "=", nestedDataProperty: "@" }, link: function(scope, element) { scope.filename = !!scope.filename ? scope.filename : "export-excel"; function generateFieldsAndHeaders(fieldsObject, fields, header) { _.forEach(fieldsObject, function(field, key) { if (!field || !key) { throw new Error("error json report fields"); } fields.push(key); header.push(field); }); return {fields: fields, header: header}; } var fieldsAndHeader = generateFieldsAndHeaders(scope.reportFields, [], []); var fields = fieldsAndHeader.fields, header = fieldsAndHeader.header; var nestedFieldsAndHeader = generateFieldsAndHeaders(scope.nestedReportFields, [], [""]); var nestedFields = nestedFieldsAndHeader.fields, nestedHeader = nestedFieldsAndHeader.header; function _convertToExcel(body, header) { return header + "\n" + body; } function _objectToString(object) { var output = ""; _.forEach(object, function(value, key) { output += key + ":" + value + " "; }); return "'" + output + "'"; } function generateFieldValues(list, rowItems, dataItem) { _.forEach(list, function(field) { var data = "", fieldValue = "", curItem = null; if (field.indexOf(".")) { field = field.split("."); curItem = dataItem; // deep access to obect property _.forEach(field, function(prop) { if (curItem !== null && curItem !== undefined) { curItem = curItem[prop]; } }); data = curItem; } else { data = dataItem[field]; } fieldValue = data !== null ? data : " "; if (fieldValue !== undefined && angular.isObject(fieldValue)) { fieldValue = _objectToString(fieldValue); } rowItems.push(fieldValue); }); return rowItems; } function _bodyData() { var body = ""; _.forEach(scope.data, function(dataItem) { var rowItems = [];var nestedBody = ""; rowItems = generateFieldValues(fields, rowItems, dataItem); //Nested Json body generation start if (scope.nestedDataProperty && dataItem[scope.nestedDataProperty].length) { _.forEach(dataItem[scope.nestedDataProperty], function(nestedDataItem) { var nestedRowItems = [""]; nestedRowItems = generateFieldValues(nestedFields, nestedRowItems, nestedDataItem); nestedBody += nestedRowItems.toString() + "\n"; }); var strData = _convertToExcel(nestedBody, nestedHeader); body += rowItems.toString() + "\n" + strData; ////Nested Json body generation end } else { body += rowItems.toString() + "\n"; } }); return body; } $timeout(function() { element.bind("click", function() { var bodyData = _bodyData(); var strData = _convertToExcel(bodyData, header); var blob = new Blob([strData], { type: "text/plain;charset=utf-8" }); return saveAs(blob, [scope.filename + ".csv"]); }); }, 1000); } }; });

答案 3 :(得分:0)

INSERT