我正在将 HTML 表格导出为 Excel 格式文件,然后将其下载为 .xls
。这在 Firefox、Chrome 等浏览器中运行良好,但在 IE 中却无法达到预期效果。
下面是我正在使用的功能。最后的 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,它会创建一个新窗口,将 HTML 输出写入其中,然后询问用户在哪里保存文件。当对话框出现时,用户被迫将文件保存为 .html
或 .txt
。
这就是奇怪的地方。尽管“另存为”框强制用户将其下载为 .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 标记的能力。
更好但更复杂的方法是实际构造一个 Base64 编码的“字符串”,如 msdn 文档中所示,但最终这足以满足该项目的需要。
或者与所有事情一样,有很多库可以为您执行此操作。
关于javascript - HTML Excel 导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34358041/