在IE 11上将HTML表格转换为Excel

时间:2017-06-13 04:10:11

标签: html excel internet-explorer-11

我想使用IE 11从html表结构创建xls(excel)文件。我在网站上经历了一些解决方案,但是它们都不适用于IE11。

我正在使用Angular2。

1 个答案:

答案 0 :(得分:0)

HTML代码:

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

类型脚本功能:

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

此代码具有跨浏览器兼容性。