需求:前端选中Excel文件后,先展示出来后再上传
安装xlsx
选择文件
这里选择文件用的el-upload
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <el-upload ref="upload" action="" accept=".xls,.xlsx" :file-list="fileList" :show-file-list="false" :auto-upload="false" :multiple="false" :on-change="onChange" :http-request="uploadFile" > <el-button slot="trigger" size="small" type="primary"> 选取文件 </el-button> </el-upload>
|
展示文件里的数据
1 2 3 4 5 6 7 8
| <el-table :data="tabelListData" style="width: 100%"> <el-table-column prop="userName" label="用户名"> </el-table-column> <el-table-column prop="displayName" label="昵称"> </el-table-column> <el-table-column prop="userRole" label="角色"> </el-table-column> <el-table-column prop="phoneNum" label="手机号"> </el-table-column> <el-table-column prop="passWord" label="密码"> </el-table-column> </el-table-column> </el-table>
|
选择文件
在选择文件夹的组件引入xlsx
1 2
| //引入xlsx import XLSX from "xlsx";
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| // 选择文件 onChange(file, filelist) { // console.log(file) const fileReader = new FileReader(); fileReader.onload = (ev) => { try { const data = ev.target.result; const workbook = XLSX.read(data, { type: 'binary' }); for (let sheet in workbook.Sheets) { //循环读取每个工作簿 const sheetArray = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]); //若当前sheet没有数据,则continue if (sheetArray.length == 0) { continue; } console.log("读取文件"); console.log(sheetArray); sheetArray.map(item => { this.tabelListData.push({ userName: item["用户名"], displayName: item["昵称"], userRole: item["角色"], phoneNum: item["手机号"], passWord: item["密码"] }) }) } } catch (e) { this.$message.warning('文件类型不正确!'); } }; //注意这里,有些blog写的不一样,根据情况可修改 fileReader.readAsBinaryString(file.raw); },
|
上传操作略。