自己最近在做一个地图的项目,需要导入excel的相关数据,处理为json之后通过接口发给strapi,网上也查看了许多资料,想借助这个机会也整理一下如何实现该功能
npm install -S xlsx
这里我用的是elementUI的el-upload组件
效果图如下:
<el-upload class="upload-demo" action="" :on-change="handleChange" :on-exceed="handleExceed" :on-remove="handleRemove" :before-remove="beforeRemove" :file-list="fileList" :limit="2" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" :auto-upload="false"> <el-button size="small" type="info" title = "只能上传xlsx/xls文件">点击上传</el-button> </el-upload>
具体每一个参数的作用可以点击上方链接查看
handleChange(file){ this.fileList.push(file); console.log(file,this.fileList); this.importExcel(file.raw); }, beforeRemove(file) { return this.$confirm(`确定移除 ${ file.name }?`); }, handleExceed(){ this.$message({ type:'warning', message:'超出上传数量!' }) }, importExcel(file){ console.log(file); let _this = this; // 通过DOM取文件数据 this.file = file; var rABS = false; //是否将文件读取为二进制字符串 var f = this.file; var reader = new FileReader(); //if (!FileReader.prototype.readAsBinaryString) { FileReader.prototype.readAsBinaryString = function(f) { var binary = ""; var rABS = false; //是否将文件读取为二进制字符串 var pt = this; var wb; //读取完成的数据 var outdata; var reader = new FileReader(); reader.onload = function(e) { var bytes = new Uint8Array(reader.result); var length = bytes.byteLength; for(var i = 0; i < length; i++) { binary += String.fromCharCode(bytes[i]); } var XLSX = require('xlsx'); if(rABS) { wb = XLSX.read(btoa(fixdata(binary)), { //手动转化 type: 'base64' }); } else { wb = XLSX.read(binary, { type: 'binary' }); } outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);//outdata就是你想要的东西 this.da = [...outdata] let arr = [] this.da.map(v => { let obj = {} obj.name = v['姓名']; obj.sex = v['性别']; console.log(obj); _this.$axios.post(这里写上传的url,JSON.stringify(obj)).then(res => { console.log(res); }) }) console.log(arr); //最终结果,数组形式 } reader.readAsArrayBuffer(f); } if(rABS) { reader.readAsArrayBuffer(f); } else { reader.readAsBinaryString(f); } } // 其中姓名和性别对应的是excel的列名
文章参考链接点我跳转