2017-06-13 18 views
0

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

我正在使用Angular2。

+0

你到目前为止尝试过什么? – lalithkumar

+0

我试过这个它没有在IE 11上工作。 https://stackoverflow.com/questions/22709029/export-the-html-table-to-excel-is-not-working-in-ie –

回答

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

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