excel的導出
阿新 • • 發佈:2017-12-26
code com undefined for 對象 自然 lob nsh 創建對象
<button onclick="downloadExl(jsono)">導出</button>
<!--
以下a標簽不需要內容
-->
<a href="" download="這裏是下載的文件名.xlsx" id="hf"></a>
<script src="http://oss.sheetjs.com/js-xlsx/xlsx.full.min.js"></script> <script> var jsono = [{ //測試數據 "保質期臨期預警(天)": "adventLifecycle", "商品標題": "title", "建議零售價": "defaultPrice", "高(cm)": "height", "商品描述": "Description", "保質期禁售(天)": "lockupLifecycle", "商品名稱": "skuName", "商品簡介": "brief", "寬(cm)": "width", "阿達": "asdz", "貨號": "goodsNo", "商品條碼": "skuNo", "商品品牌": "brand", "凈容積(cm^3)": "netVolume", "是否保質期管理": "isShelfLifeMgmt", "是否串號管理": "isSNMgmt", "商品顏色": "color", "尺碼": "size", "是否批次管理": "isBatchMgmt", "商品編號": "skuCode", "商品簡稱": "shortName", "毛重(g)": "grossWeight", "長(cm)": "length", "英文名稱": "englishName", "凈重(g)": "netWeight", "商品分類": "categoryId", "這裏超過了": 1111.0, "保質期(天)": "expDate" }]; var tmpDown; //導出的二進制對象 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 = [];//用來保存轉換好的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); //設置區域,比如表格從A1到D10 var tmpWB = { SheetNames: [‘mySheet‘], //保存的表標題 Sheets: { ‘mySheet‘: Object.assign({}, tmpdata, //內容 { ‘!ref‘: outputPos[0] + ‘:‘ + outputPos[outputPos.length - 1] //設置填充區域 }) } }; tmpDown = new Blob([s2ab(XLSX.write(tmpWB, {bookType: (type == undefined ? ‘xlsx‘:type),bookSST: false, type: ‘binary‘}//這裏的數據是用來定義導出的格式類型 ))], { type: "" }); //創建二進制對象寫入轉換好的字節流 var href = URL.createObjectURL(tmpDown); //創建對象超鏈接 document.getElementById("hf").href = href; //綁定a標簽 document.getElementById("hf").click(); //模擬點擊實現下載 setTimeout(function() { //延時釋放 URL.revokeObjectURL(tmpDown); //用URL.revokeObjectURL()來釋放這個object URL }, 100); } function s2ab(s) { //字符串轉字符流 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; } // 將指定的自然數轉換為26進制表示。映射關系:[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>
excel的導出