您好,登錄后才能下訂單哦!
小編給大家分享一下JavaScript如何導出Excel,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
<script src="https://lib.baomitu.com/jquery/3.3.1/jquery.min.js"> </script> <script crossorigin="anonymous" integrity="sha384-m/TzZt0ykrLNcWKIbWS5Ki26N6AvwYe1BnqHriftAK8tohV7lhiLyXwUI3C8YdOD" src="https://lib.baomitu.com/xlsx/0.14.1/xlsx.full.min.js"> </script> function saveAs(obj, fileName) {//當然可以自定義簡單的下載文件實現方式 var tmpa = document.createElement("a"); tmpa.download = fileName || "下載"; tmpa.href = URL.createObjectURL(obj); //綁定a標簽 tmpa.click(); //模擬點擊實現下載 setTimeout(function () { //延時釋放 URL.revokeObjectURL(obj); //用URL.revokeObjectURL()來釋放這個object URL }, 100); } const wopts = { bookType: 'xlsx', bookSST: false, type: 'binary' };//這里的數據是用來定義導出的格式類型 // const wopts = { bookType: 'csv', bookSST: false, type: 'binary' };//ods格式 // const wopts = { bookType: 'ods', bookSST: false, type: 'binary' };//ods格式 // const wopts = { bookType: 'xlsb', bookSST: false, type: 'binary' };//xlsb格式 // const wopts = { bookType: 'fods', bookSST: false, type: 'binary' };//fods格式 // const wopts = { bookType: 'biff2', bookSST: false, type: 'binary' };//xls格式 function downloadExl(data, name) { const wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} }; wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(data);//通過json_to_sheet轉成單頁(Sheet)數據 saveAs(new Blob([s2ab(XLSX.write(wb, wopts))], { type: "application/octet-stream" }), name + '.' + (wopts.bookType=="biff2"?"xls":wopts.bookType)); } function s2ab(s) { if (typeof ArrayBuffer !== 'undefined') { var buf = new ArrayBuffer(s.length); var view = new Uint8Array(buf); for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF; return buf; } else { var buf = new Array(s.length); for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF; return buf; } } function downloadXLSById(idName,fileName){ var title = new Array(); $(`#${idName} table thead tr th`).each(function(i,v){ title.push(v.textContent); }); var jsonData = []; $("#"+idName+" table tbody tr").each(function(i,v){ var data = {}; v.childNodes.forEach(function(value,index){ data[title[index]] = $.trim(value.textContent); }); jsonData.push(data); }); downloadExl(jsonData,fileName); }
調用方式
downloadXLSById(idName,fileName);
idName : table 的上級p的 id值
fileName : 保存的文件名稱
看完了這篇文章,相信你對JavaScript如何導出Excel有了一定的了解,想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。