excel download in angular

 download(){

    if(this.fromdate2==undefined){
      this.filename="AllIssues";
    }else{

      this.filename=this.fromdate2;
    }
   
   
    this.downloadFile(this.jsonData, this.filename);
  }

 
  downloadFile(data, filename='data') {
    let date;
    if(this.fromdate2==undefined){
   date='';
    }else{
      date='Month: '+this.fromdate2;
    }
    let csvData = this.ConvertToCSV(data, ['ArmyNo','Name', 'Rank','Unit' ,'Issue','ReportedOn', 'ResolvedOn']);
    console.log(csvData);  
    let blob;
    if(date==''){
       blob = new Blob(['\ufeff' + csvData], { type: 'text/csv;charset=utf-8;' });
   
    }else{
      blob = new Blob(['\ufeff' +  date + '\r\n' + 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 = 'S.No,';

     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';
     }
     console.log(str);
     return str;
     
 }

Comments

Popular posts from this blog

Your app currently targets API level 27 and must target at least API level 28 to ensure it is built on the latest APIs optimized for security and performance. Change your app's target API level to at least 28

ionic project creation

change root user in ubuntu