JS 匯出表格
阿新 • • 發佈:2020-12-22
來源網路,作了簡單優化優化
//匯出excel function toExcel(bookname,targetControlerID) { //window.location.href='<%=basePath%>pmb/excelShowInfo.do'; //獲取表格 try { var exportFileContent = document.getElementById(targetControlerID).outerHTML; } catch (e) { alert("請查詢後再點選匯出!"); return; } //設定格式為Excel,表格內容通過btoa轉化為base64,此方法只在檔案較小時使用(小於1M) //exportFileContent=window.btoa(unescape(encodeURIComponent(exportFileContent))); //var link = "data:"+MIMEType+";base64," + exportFileContent; //使用Blob var blob = new Blob([exportFileContent], { type: "text/plain;charset=utf-8" }); //解決中文亂碼問題 blob = new Blob([String.fromCharCode(0xFEFF), blob], { type: blob.type }); if ("msSaveOrOpenBlob" in navigator) { //相容ie window.navigator.msSaveOrOpenBlob(blob, bookname); return; } //設定連結 var link = window.URL.createObjectURL(blob); var a = document.createElement("a"); //建立a標籤 a.download = bookname; //設定被下載的超連結目標(檔名) a.href = link; //設定a標籤的連結 document.body.appendChild(a); //a標籤新增到頁面 a.click(); //設定a標籤觸發單擊事件 document.body.removeChild(a); //移除a標籤 }
使用在前端需要匯出的button上新增 onclick="toExcel('DieChecked.xls', 'MainContent_gdvDieChecked') 即可……