0

I want to create xls(excel) file from html table structure using IE 11. I have gone through some solutions on site, however none of them works on IE11.

I am using Angular2.

1 Answers1

0

The HTML code:

<input type="button" (click)="tableToExcel('testTable', 'W3C Example Table')" value="Export to Excel">

The type script Function:

tableToExcel(table, name){
  let tab_text = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
  tab_text = tab_text + '<head><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>';
  tab_text = tab_text + '<x:Name>Test Sheet</x:Name>';
  tab_text = tab_text + '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet>';
  tab_text = tab_text + '</x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>';
  tab_text = tab_text + "<table border='1px'>";
  tab_text = tab_text + ( < HTMLScriptElement > document.getElementById(table)).innerHTML;
  tab_text = tab_text + '</table></body></html>';
  let uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(decodeURIComponent(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }

  if (window.navigator.userAgent.indexOf("MSIE") > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./) || !!navigator.userAgent.match(/Trident\/7\./) || window.navigator.userAgent.indexOf("Edge") > -1) {
    if (window.navigator.msSaveBlob) {
      var blob = new Blob([tab_text], {type: "application/csv;charset=utf-8;"});
      navigator.msSaveBlob(blob, 'Test file.xls');
    } 
  }else{ 
   if (!table.nodeType) table = document.getElementById(table) 
     var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML} 
     window.location.href = uri + base64(format(template, ctx)) 
   } 
  }

This code has cross browser compatibility.

Samvel Aleqsanyan
  • 2,812
  • 4
  • 20
  • 28