在Angular中导出JSON到CSV

rkue9o1l  于 2023-07-01  发布在  Angular
关注(0)|答案(4)|浏览(139)

我正在寻找使用Angular将JSON对象转换为CSV格式的方法。我遇到了这个https://www.npmjs.com/package/jsonexport,这正是我想要使用的东西,但我不确定我是否可以在Angular中使用它(似乎是特定于节点的?)如果没有,有没有现成的指令,等等,我可以喂一些JSON到得到CSV回来。
有人能给我指出一些有用的例子吗?我看了一下,它们似乎很少,而且我发现它们似乎只能科普非常基本的平面JSON结构。
谢谢

iswrvxsc

iswrvxsc1#

您可以使用这个简单的代码从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;
    }
  }
hgqdbh6s

hgqdbh6s2#

试试这个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>
f8rj6qna

f8rj6qna3#

generateUserCSV() {
    this.emailService.getAllEmail().subscribe((res) => { this.downloadFile(res, 'emails') })
  }

  downloadFile(data, filename = 'data') {
    let csvData = this.ConvertToCSV(data, ['email', 'firstname', 'lastname']);
    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", filename + ".csv");
    dwldLink.style.visibility = "hidden";
    document.body.appendChild(dwldLink);
    dwldLink.click();
    document.body.removeChild(dwldLink);
  }

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

    for (let index in headerList) {
      row += headerList[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 += ',' + array[i][head];
      }
      str += line + '\r\n';
    }
    return str;
  }
a8jjtwal

a8jjtwal4#

在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代码:

<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

相关问题