【问题标题】:Convert HTML Table to Excel on IE 11在 IE 11 上将 HTML 表格转换为 Excel
【发布时间】:2017-06-13 04:10:11
【问题描述】:

我想使用 IE 11 从 html 表结构创建 xls(excel) 文件。我在现场浏览了一些解决方案,但它们都不适用于 IE11。

我正在使用 Angular2。

【问题讨论】:

标签: html excel internet-explorer-11


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-21
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    • 1970-01-01
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多