vue中XLSX解析excel文件
引入XLSX
1 import XLSX from 'xlsx' 2 import Vue from 'vue' 3 const vm = new Vue(); 4 5 async function readExcel (file) { 6 const types = file.name.split('.'); 7 const type = types[types.length - 1]; 8 const fileType = [ 9 'xlsx', 'xls', 'XLSX', 'XLS' 10 ].some(item => item == type); 11 if (!fileType) { 12 vm.$message.error('格式错误!请重新选择') 13 return 14 } 15 16 const result = []; 17 18 const loaded = (row) => { 19 return new Promise((resolve) =>{ 20 const reader = new FileReader(); 21 reader.onload = function(e) { 22 const data = e.target.result; 23 const wb = XLSX.read(data, { 24 type: 'binary' 25 }); 26 27 wb.SheetNames.forEach((sheetName) => { 28 result.push( 29 XLSX.utils.sheet_to_json(wb.Sheets[sheetName], {header:1,defval:''}) 30 /* { 31 sheet: XLSX.utils.sheet_to_json(wb.Sheets[sheetName], {header:1,defval:''}) 32 } */ 33 ) 34 }); 35 resolve(true) 36 }; 37 reader.readAsBinaryString(row) 38 }) 39 } 40 41 await loaded(file.raw) 42 return result; 43 } 44 45 export { readExcel }
使用
1 <el-upload ref="upload" accept=".xls,.xlsx" action="" :auto-upload="false" :on-change="handleUpload" :show-file-list="false"> 2 <el-button type="primary" plain>选择文件</el-button> 3 <span>只能上传xls或xlsx文件</span> 4 <span>{{form.fileName}}</span> 5 </el-upload> 6 7 8 handleUpload (file,fileList) { 9 // readExcel(file) 10 if(fileList && fileList.length) { 11 this.ruleForm.fileText = []; 12 this.ruleForm.fileName = fileList[fileList.length - 1].name; 13 readExcel(file).then((res) =>{ 14 if (res) { 15 const obj = res[0]; 16 for(let i = 0; i < obj.length; i ++) { 17 const arr = {} 18 arr.itemIds = obj[i][0]; 19 arr.subThemeTitle = obj[i][1]; 20 this.ruleForm.fileText.push(arr); 21 } 22 } 23 }) 24 } 25 ,