简体   繁体   English

如何在angular4中将对象数组导出到excel?

[英]How to export array of objects to an excel in angular4?

I have an array of objects as shown below 我有一个对象数组,如下所示

    [
        {   "FirstName": "John", 
            "LastName": "Parker", 
            "Age": "23", 
            "Cat": "23g",
            "SOP": "Active"
        },
        {   "FirstName": "Rose", 
            "LastName": "Jackson", 
            "Age": "44", 
            "Cat": "44g",
            "SOP": "InActive"
        }
    ]

how can i export this data along with the logo of the company to the excel and download the same. 我该如何将这些数据以及公司logo导出到Excel并下载。

Any suitable plugin to write objects data and logo image to excel? 有合适的插件可以将objects datalogo image写入Excel吗?

you can use this function , it works fine with me 您可以使用此功能,对我来说效果很好

//DOWNLOAD
  download(){
    var csvData = this.ConvertToCSV( this.data);
    var a = document.createElement("a");
    a.setAttribute('style', 'display:none;');
    document.body.appendChild(a);
    var blob = new Blob([csvData], { type: 'text/csv' });
    var url= window.URL.createObjectURL(blob);
    a.href = url;
    var x:Date = new Date();
    var link:string ="filename_" + x.getMonth() +  "_" +  x.getDay() + '.csv';
    a.download = link.toLocaleLowerCase();
    a.click();

  }


// convert Json to CSV data in Angular2
  ConvertToCSV(objArray) {
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';
    var row = "";

    for (var index in objArray[0]) {
        //Now convert each value to string and comma-separated
        row += index + ',';
    }
    row = row.slice(0, -1);
    //append Label row with line break
    str += row + '\r\n';

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

The better approach is to do this from backend side but still, there are some packages available to do same, check it out 更好的方法是从后端执行此操作,但是仍然有一些软件包可以执行相同操作,请查看

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

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