下載xlsx-style
npm install xlsx-style
xlsx-style核心模塊 在 你安裝路徑\node_modules\xlsx-style\dist
2.示例代碼
復(fù)制出 文件xlsx.full.min.js
編寫示例代碼:
<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>示例</title></head><body> <script src="./xlsx.full.min.js"></script> <script> function saveAs(obj, fileName) { var tmpa = document.createElement("a"); tmpa.download = fileName || "下載"; tmpa.href = URL.createObjectURL(obj); tmpa.click(); setTimeout(function () { URL.revokeObjectURL(obj); }, 100); } var jsono = [{ "id": 1, "合并的列頭1": "數(shù)據(jù)11", "合并的列頭2": "數(shù)據(jù)12", "合并的列頭3": "數(shù)據(jù)13", "合并的列頭4": "數(shù)據(jù)14", }, { "id": 2, "合并的列頭1": "數(shù)據(jù)21", "合并的列頭2": "數(shù)據(jù)22", "合并的列頭3": "數(shù)據(jù)23", "合并的列頭4": "數(shù)據(jù)24", }]; const wopts = { bookType: 'xlsx', bookSST: true, type: 'binary', cellStyles: true }; function downloadExl(json, type) { var tmpdata = json[0]; json.unshift({}); var keyMap = []; //獲取keys for (var k in tmpdata) { keyMap.push(k); json[0][k] = k; } var tmpdata = [];//用來保存轉(zhuǎn)換好的json json.map((v, i) => keyMap.map((k, j) => Object.assign({}, { v: v[k], position: (j > 25 ? getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1) }))).reduce((prev, next) => prev.concat(next)).forEach((v, i) => tmpdata[v.position] = { v: v.v }); var outputPos = Object.keys(tmpdata); //設(shè)置區(qū)域,比如表格從A1到D10 tmpdata["B1"].s = { font: { sz: 14, bold: true, color: { rgb: "FFFFAA00" } }, fill: { bgColor: { indexed: 64 }, fgColor: { rgb: "FFFF00" } } };//<====設(shè)置xlsx單元格樣式 tmpdata["!merges"] = [{ s: { c: 1, r: 0 }, e: { c: 4, r: 0 } }];//<====合并單元格 var tmpWB = { SheetNames: ['mySheet'], //保存的表標(biāo)題 Sheets: { 'mySheet': Object.assign({}, tmpdata, //內(nèi)容 { '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] //設(shè)置填充區(qū)域 }) } }; tmpDown = new Blob([s2ab(XLSX.write(tmpWB, { bookType: (type == undefined ? 'xlsx' : type), bookSST: false, type: 'binary' }//這里的數(shù)據(jù)是用來定義導(dǎo)出的格式類型 ))], { type: "" }); saveAs(tmpDown, "這里是下載的文件名" + '.' + (wopts.bookType == "biff2" ? "xls" : wopts.bookType)); } function getCharCol(n) { let temCol = '', s = '', m = 0 while (n > 0) { m = n % 26 + 1 s = String.fromCharCode(m + 64) + s n = (n - m) / 26 } return s } 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; } } </script> <button onclick="downloadExl(jsono)">導(dǎo)出</button></body></html>
相信看了本文案例你已經(jīng)掌握了方法,更多精彩請關(guān)注Gxl網(wǎng)其它相關(guān)文章!
相關(guān)閱讀:
如何使用canvas來制作好用的涂鴉畫板
如何使用s-xlsx實(shí)現(xiàn)Excel 文件導(dǎo)入和導(dǎo)出(下)
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com