0

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.

Any suitable plugin to write objects data and logo image to excel?

1
  • i recommand you to do this in back-end side. Commented Apr 26, 2018 at 7:06

2 Answers 2

6

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;
  }
Sign up to request clarification or add additional context in comments.

1 Comment

This is awesome! Your "ConvertToCSV" doesn't escape already present commas though, any idea on how to cater for this?
1

The better approach is to do this from backend side but still, there are some packages available to do same, check it out

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.