使用xlsx.full.min.js處理excel表格(將JSON數(shù)據(jù)轉(zhuǎn)化為excel表并實(shí)現(xiàn)下載)
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="./xlsx.full.min.js"></script> </head> <body> <button onclick="downloadExl(jsono)">導(dǎo)出</button> <!-- 以下a標(biāo)簽不需要內(nèi)容 --> <a href="" download="這里是下載的文件名.xlsx" id="hf"></a> <script> var jsono = [{ //測(cè)試數(shù)據(jù) "保質(zhì)期臨期預(yù)警(天)": "adventLifecycle", "商品標(biāo)題": "title", "建議零售價(jià)": "defaultPrice", "高(cm)": "height", "商品描述": "Description", "保質(zhì)期禁售(天)": "lockupLifecycle", "商品名稱(chēng)": "skuName", "商品簡(jiǎn)介": "brief", "寬(cm)": "width", "阿達(dá)": "asdz", "貨號(hào)": "goodsNo", "商品條碼": "skuNo", "商品品牌": "brand", "凈容積(cm^3)": "netVolume", "是否保質(zhì)期管理": "isShelfLifeMgmt", "是否串號(hào)管理": "isSNMgmt", "商品顏色": "color", "尺碼": "size", "是否批次管理": "isBatchMgmt", "商品編號(hào)": "skuCode", "商品簡(jiǎn)稱(chēng)": "shortName", "毛重(g)": "grossWeight", "長(zhǎng)(cm)": "length", "英文名稱(chēng)": "englishName", "凈重(g)": "netWeight", "商品分類(lèi)": "categoryId", "這里超過(guò)了": 1111.0, "保質(zhì)期(天)": "expDate" }]; var tmpDown; //導(dǎo)出的二進(jìn)制對(duì)象 function downloadExl(json, type) { var tmpdata = json[0]; json.unshift({}); var keyMap = []; //獲取keys //keyMap =Object.keys(json[0]); for (var k in tmpdata) { keyMap.push(k); json[0][k] = k; } var tmpdata = [];//用來(lái)保存轉(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 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ù)是用來(lái)定義導(dǎo)出的格式類(lèi)型 ))], { type: "" }); //創(chuàng)建二進(jìn)制對(duì)象寫(xiě)入轉(zhuǎn)換好的字節(jié)流 var href = URL.createObjectURL(tmpDown); //創(chuàng)建對(duì)象超鏈接 document.getElementById("hf").href = href; //綁定a標(biāo)簽 document.getElementById("hf").click(); //模擬點(diǎn)擊實(shí)現(xiàn)下載 setTimeout(function() { //延時(shí)釋放 URL.revokeObjectURL(tmpDown); //用URL.revokeObjectURL()來(lái)釋放這個(gè)object URL }, 100); } function s2ab(s) { //字符串轉(zhuǎn)字符流 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; } // 將指定的自然數(shù)轉(zhuǎn)換為26進(jìn)制表示。映射關(guān)系:[0-25] -> [A-Z]。 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 } </script> </body> </html> 該文章在 2023/5/22 18:21:00 編輯過(guò) |
關(guān)鍵字查詢(xún)
相關(guān)文章
正在查詢(xún)... |