官方解释:Blob是一个类文件的不可变的原始数据对象,非javascript原生数据类型,File对象就是继承自Blob对象,且在Blob的基础上进行扩展,以便支持用户系统上的文件。
先贴下载代码
var html = '<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>Sheet1</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>' + document.getElementsByClassName("projectTable")[0].outerHTML + "</body></html>"; var blob = new Blob([html], { type: "application/vnd.ms-excel" });
var a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = "工程统计表.xls"; document.body.appendChild(a); a.onclick = function() { document.body.removeChild(a); }; a.click();
如果直接使用Blob下载,其他浏览器正常但在ie会出现这样的问题无法正常下载

百度发现:微软在ie10 和ie11中有两个能解决这个问题的方法:window.navigator.msSaveBlob和window.navigator.msSaveOrOpenBlob 方法,这两个方法的区别在于,The Navigator.msSaveOrOpenBlob() method saves the File or Blob to disk. This method behaves in the same way as Navigator.msSaveBlob() except that this enables the file open option.(前者只有保存,后者有保存和打开两个选项)
msSaveOrOpenBlob 官方解释:Launches the associated application for a File or Blob.(启动File或Blob的关联应用程序)
解决方法:
var html = '<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>Sheet1</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>' + document.getElementsByClassName("projectTable")[0].outerHTML + "</body></html>"; var blob = new Blob([html], { type: "application/vnd.ms-excel" }); //判断ie if (window.navigator && window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveOrOpenBlob(blob, "工程统计表.xls"); } else { var a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = "工程统计表.xls"; document.body.appendChild(a); a.onclick = function() { document.body.removeChild(a); }; a.click(); }
