多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
在写后台管理系统中。我们往往需要实现做数据的导入导出功能。这次先写导入的功能部分,导出功能暂时先不写。 #### 示例一:是基于vue的前端UI框架iview写的。具体代码如下所示。 ~~~ <style lang="less"> .info-btn { position: relative; width: 44px; height: 24px; z-index: 1; .input-page { position: absolute; left: 0; top: 0; width: 44px; height: 24px; border-color: #57c5f7; outline: none; background-color: transparent; filter:alpha(opacity=0); -moz-opacity:0; -khtml-opacity: 0; opacity: 0; font-size: 8px; // display: none; color: #fff; z-index: 99; } .info-font { position: absolute; left: 0; top: 0; width: 100%; height: 100%; text-align: center; line-height: 24px; z-index:2; } } </style> // 隐藏了导入文件的按钮。使用自定义的按钮 <Button type="info" @change="importf()" class="info-btn"> <input type="file" @change="importf()" class="input-page" /> <span class="info-font">导入</span> </Button> ~~~ 为了容易区别,我把js的代码提取出来 ~~~ data: { rABS: false } // 具体方法 importf () {//导入 let that =this; let file = event.target.files; if (!file) { return; } var f = file[0]; { var reader = new FileReader(); var name = f.name; reader.onload = function (e) { var data = e.target.result; var wb; if (that.rABS) { wb = XLSX.read(data, { type: 'binary' }); } else { var arr = that.fixdata(data); wb = XLSX.read(btoa(arr), { type: 'base64' }); } // 打印出excel文件转成普通的json数据 console.log(JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]))) }; if (that.rABS) reader.readAsBinaryString(f); else reader.readAsArrayBuffer(f); } }, fixdata (data) { var o = "", l = 0, w = 10240; for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w))); o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w))); return o; } ~~~ 示例二:纯原生js写的导入功能 [转载于纯原生的js实现excel文件的导入功能](https://www.jianshu.com/p/044c183edf42) ~~~ <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="http://oss.sheetjs.com/js-xlsx/xlsx.full.min.js"></script> </head> <body> <input type="file" onchange="importf(this)" /> <div id="demo"></div> <script> var rABS = false; //导入功能 function importf(obj) { if (!obj.files) { return; } var f = obj.files[0]; { var reader = new FileReader(); var name = f.name; reader.onload = function (e) { var data = e.target.result; var wb; if (rABS) { wb = XLSX.read(data, { type: 'binary' }); } else { var arr = fixdata(data); wb = XLSX.read(btoa(arr), { type: 'base64' }); } document.getElementById("demo").innerHTML = JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])); }; if (rABS) reader.readAsBinaryString(f); else reader.readAsArrayBuffer(f); } } function fixdata(data) { var o = "", l = 0, w = 10240; for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w))); o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w))); return o; } </script> </body> </html>