HTML excel导出

我将HTML表格导出为Excel格式文件,然后将其作为.xls文件下载。 这在Firefox,Chrome等工作正常,但不是在IE浏览器预期。

以下是我正在使用的function。 最后的if语句发现浏览器是IE还是其他。

 function exportTable(obj) { var tab_text="<table border='2px'><tr>"; var textRange; var j=0; tab = obj; for(j = 0 ; j < tab.rows.length ; j++){ tab_text=tab_text+tab.rows[j].innerHTML+"</tr>"; //tab_text=tab_text+"</tr>"; } tab_text=tab_text+"</table>"; tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if you want links in your table tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if you want images in your table tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // removes input params var ua = window.navigator.userAgent; var msie = ua.indexOf("MSIE "); if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer { txtArea1 = window.open(); txtArea1.document.open("txt/html","replace"); txtArea1.document.write(tab_text); txtArea1.document.close(); txtArea1.focus(); sa=txtArea1.document.execCommand("SaveAs",false,"export.xls"); txtArea1.window.close() } else { //other browser not tested on IE 11 sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text)); return (sa); } } 

如果是IE,则会创build一个新窗口,将HTML输出写入到该窗口,然后询问用户保存文件的位置。 当对话框出现时,用户被迫将文件保存为.html.txtexportPopup

这是奇怪的地方。 尽pipe“另存为”框强制用户将其下载为.html.txt但文件本身保存为.xls

是否可以禁用此提示? 还是有另外的解决方法吗? 我不希望最终用户被这个困惑。

尝试使用隐藏的iframe而不是新窗口。 这为我解决了很多问题。 为了支持IE9,我结束了这个片段:

 if (event.data.browser !== 'IE') { $.util.open('data:application/vnd.ms-excel,' + event.data.content); return true; } else { // The iframe already has to be included in the HTML, or you'll get a 'no access error'. frame.document.open("txt/html","replace"); frame.document.write(event.data.content); frame.document.close(); frame.focus(); command = frame.document.execCommand("SaveAs", true, "data_table.xls"); return command; } 

唯一的缺点是,它不是一个“真正的”excel .xls文件,直到你第一次打开它,并保存为.xls这种技术只是利用Excel的能力来理解基本的HTML标记。

一个更好,但更复杂的方法是实际构build一个如msdn文档中所示的base64编码“string”,但最终这个项目已经足够了。

或者像所有的事情一样,有很多图书馆会为你做这个。