Ms_ Dev

Ms_ Dev

  • NA
  • 236
  • 88.1k

Excel file export & downloading issue in Angular6/Typescript

Mar 14 2019 10:33 PM
Hi All,
 
I have the following code in my .ts file which is creating excel export file but while opening the file in MS EXCEL, it is not opening and showing error as file has been currupted or bad file extension. 
  1. ExportExcel(objArray: any, filename: string) {  
  2.     var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;  
  3.     var str = '<table>';  
  4.     var row = "<tr>";  
  5.       
  6.     for (var index in objArray[0]) {  
  7.       row += '<th>' + index + '</th>'   
  8.     }  
  9.       row = row.slice(0, -5);  
  10.     str += row + '</tr>';  
  11.   
  12.     for (var i = 0; i < array.length; i++) {  
  13.       var line = '<tr>';  
  14.       for (var index in array[i]) {  
  15.          line += '<td>' + array[i][index] + '</td>';  
  16.       }  
  17.       str += line + '</tr>';  
  18.     }  
  19.   
  20.     str += '</table>';  
  21.     var a = document.createElement("a");  
  22.     a.setAttribute('style''display:none;');  
  23.     document.body.appendChild(a);  
  24.     var blob = new Blob([str], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });  
  25.     var url = window.URL.createObjectURL(blob);  
  26.     a.href = url;  
  27.     a.download = filename + '.xlsx';  
  28.     a.click();  
  29.   
  30.     str = '';  
  31.     row = '';  
  32.   }  
 Any help on this would be highly appriciated.

Answers (1)