Thursday 10 May 2018

Ng4-Export JSON to CSV

Ng5- Download JSON to CSV
template.html
-------------
<a id="Download" title="Download " (click)="downloadCSV()">
            <img src="assets/svg/icons/Download.svg" />
</a>

component.ts
------------
import {ExportCSV} from '../../../exportCSV';

construct(private _exportService:ExportCSV){}

Data = Response Array from Web API service data

downloadCSV() {
    this.downloadData = this.Data.map(item => {
          let val =  new Date(item.eeeDate.split(' ')[0]);
          var day = val.getDate();
          var monthIndex = val.getMonth();
          var year = val.getFullYear();
          let months=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
          let mm = months[monthIndex];
          item.eeeDate =day +" " + mm + " " + year;
          return item;
    });
let jsonData=this.allData;
    let level=this.url[3];
    let id=this.url[4];
    let header=['header1 Name','h2name','h3 Number','h4 Id','h5','h6 Version','h7  Date'];
    let keys=['h1k1','h2k2','h3k3','h4k4','h5k5','h6k6','h7k7'];
    let filename= 'CDE'; 
    this._exportService.exportCSV(keys,header,jsonData,filename,level,id);


shared->exportCSVService:
------------
import { Injectable } from '@angular/core';

@Injectable()
export class ExportCSV  {
  constructor() {}
  exportCSV(keys,header,jsonData,filename,level,id){
    let filteredData = this.getFilterJSON(keys,jsonData);
    let ReportTitle = filename+ " " +level+" "+id;
    let ShowLabel = true;
    var arrData = typeof filteredData != 'object' ? JSON.parse(filteredData) : filteredData;
    var CSV = '';
    if (ShowLabel) {
      var row = "";
      for (let index=0;index<header.length;index++) {
        row += header[index] + ',';
      }
      row = row.slice(0, -1);
      CSV += row + '\r\n';
    }
    for (var i = 0; i < arrData.length; i++) {
      var row = "";
      for (var index in arrData[i]) {
        row += '"' + arrData[i][index] + '",';
      }
      row.slice(0, row.length - 1);
      CSV += row + '\r\n';
    }

    if (CSV == '') {
      console.log("Invalid data");
      return;
    }
    var fileName = ReportTitle.replace(/ /g, "_");
    var uri = 'data:text/csv;charset=utf-8,' + encodeURI(CSV);
    var link = document.createElement("a");
    link.href = uri;
    link.download = fileName + ".csv";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
    getFilterJSON(keys,jsonObj){
     let k=[];
     for(let i=0;i<jsonObj.length;i++){
         let item = {};
         for(let m=0;m<keys.length;m++){
         item[keys[m]]=jsonObj[i][keys[m]];
         }
        k.push(item);
       }   
       return k;
      }

No comments:

Post a Comment