火狐不能html转execl,使用Blob无法在FireFox中使用Excel导出JavaScript

我的问题的答案如下所述.

问题是,为了让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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值