1

Below is example for exporting JSON to CSV:

import { Angular7Csv } from 'angular7-csv/Angular7-csv';

var data = [
 {
   name: "Test 1",
   age: 13,
   average: 8.2,
   approved: true,
   description: [{"Status": "Pass", "TimeStamp": "2019-03-12 08:19:50", "UserID": "KG19932"}]
},
 {
   name: 'Test 2',
   age: 11,
   average: 8.2,
   approved: true,
   description: [{"Status": "Pass", "TimeStamp": "2019-03-12 08:19:50", "UserID": "KG19932"}]

 },
 {
   name: 'Test 4',
   age: 10,
   average: 8.2,
   approved: true,
   description: [{"Status": "Pass", "TimeStamp": "2019-03-12 08:19:50", "UserID": "KG19932"}]
}
];

new Angular7Csv(data, 'My Report');

.csv file getting downloaded successfully but in Description column value getting as [object object]. I have tried JSON.stringify and JSON.Parse but no luck. Anyone has solution for this??

0

2 Answers 2

2

For more precise output you can use this code as well

You can export from JSON to CSV using this simple code. This code solve the many basic issues like, problems with the separator, custom heading, skip empty column and add - in place of the empty data for a particular column. Refer this github link to solve all the issue regarding CSV export in Angular.

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

Consider this as you JSON data

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

You can download you csv using these functions

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

And to edit the format of the CSV you can add this function

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

In case of values with comma, You can use this function to remove the comma and consider it as one single value

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

1 Comment

Instead of removing the comma, you can just enclose it in double quotes ` if (typeof data === 'string') { // Escape double quotes by replacing " with "" let newData = data.replace(/"/g, '""'); // Enclose in double quotes if value contains commas, newlines, or double quotes if (newData.includes(',') || newData.includes('\n') || newData.includes('"')) { newData = "${newData}"; } return newData; } `
1

just stringfy the description

     data.forEach(x=>{
          x.description=JSON.stringify(x.description);
        });
     new Angular7Csv(data, 'My Report');

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.