我的问题的答案如下所述.
问题是,为了让FireFox对a.click()做出反应并显示它的文件对话框,很快就调用了行window.URL.revokeObjectURL(url).所以,我刚刚使用setTimeout为行window.URL.revokeObjectURL(url)添加了一个延迟.此更改使其在FireFox中可用.当然,它也适用于Chrome.
更新后的代码如下所示,最后一行代码只有一处变化.此外,在FireFox中使用此更改的演示是:http://js.do/sun21170/84977
用于导出的Blob代码(适用于FireFox和Chrome)
//export data in Chrome or FireFox
//this works in Chrome as well as in FireFox
sa = true;
var myBlob = new Blob( [table] , {type:'text/html'});
var url = window.URL.createObjectURL(myBlob);
var a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.download = "newfile.xls";
a.click();
//adding some delay in removing the dynamically created link solved the problem in FireFox
setTimeout(function() {window.URL.revokeObjectURL(url);},0);
虽然上面的代码运行完美,但我认为在导出到xls文件时,最好使用类型:’application / vnd.ms-excel,即使表变量包含html字符串.
这个小改动使FireFox自动使用Excel作为打开导出文件的默认程序,否则FireFox使用Laucnch Windows应用程序(默认)打开文件.我的笔记本电脑上的默认应用是Edge浏览器.
var myBlob = new Blob( [table] , {type:'application/vnd.ms-excel'});
如果您想在旧版IE浏览器中使用100%客户端方法,则无法使用Blob对象,因为它在较旧的IE浏览器中不可用,但您可以使用下面的代码片段中的其他方法.
在IE< = IE 11中将Html导出到Excel,包括IE 8和IE 9
function ExportTabletoExcelInOldIE(table)
{
//table variable contains the html to be exported to Excel
var sa = null;
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0) // If old Internet Explorer including IE 8
{
//make sure you have an empty div with id of iframeDiv in your page
document.getElementById('iframeDiv').innerHTML = '';
txtArea1.document.open("txt/html", "replace");
txtArea1.document.write(table);
txtArea1.document.close();
txtArea1.focus();
sa = txtArea1.document.execCommand("SaveAs", true, "DataExport.xls");
document.getElementById('iframeDiv').innerHTML = "";
}
return (sa);
}
要使上述IE特定代码起作用,请在页面标记中添加以下内容.
在较旧的IE浏览器中导出时需要空Div