1.读取方法 需要下载xlsx依赖
export const readExcelFile = (file) => {return new Promise((resolve, reject) => {let reader = new FileReader();reader.readAsBinaryString(file.raw);reader.onload = (ev) => {try {let dataBinary = ev.target.result;let workBook = XLSX.read(dataBinary, { type: "binary", cellDates: true });let workSheet = workBook.Sheets[workBook.SheetNames[0]];const data = XLSX.utils.sheet_to_json(workSheet); //这里已经能拿到转换后的jsonresolve(data);} catch (err) {reject(err);}};reader.onerror = (ev) => {reject("文件读取失败");};});
};
2.使用
<el-upload action=""accept=".xls,.xlsx"ref="uploadVm":auto-upload="false":show-file-list="false":limit="1":on-exceed="handleExceed":on-change="handleFileChange"><div class="btn fr_c fj_c cp" slot="reference">导入销售机会 /></div>
</el-upload>
//文件超出覆盖handleExceed(files, fileList) {this.$set(fileList[0], "raw", files[0]); //raw就是指文件this.$set(fileList[0], "name", files[0].name); //name就是指文件名this.$refs.uploadVm.clearFiles(); //删除所有上传的文件this.$refs.uploadVm.handleStart(files[0]); //handleStart()指的是手动选择文件,Element Plus 的el-upload有说明},//change事件handleFileChange(file) {readExcelFile(file).then((data) => {let excelData = data.map((item) => {return {saleName: item["销售机会名称"],customerName: item["客户名称"],};});}).catch((err) => {this.$message.error("文件读取失败");this.$refs.uploadVm.clearFiles();});},
如果后端配合可以通过前端传递formData对象 后端返回list那就不需要前端读取了
//点击文件上传
const handleFileChange = debounce((file, fileArr) => {noDatauploadRef.value && noDatauploadRef.value.clearFiles();uploadRef.value && uploadRef.value.clearFiles();if (!checkFileSize(fileArr)) return;//整理form对象let formData = new FormData();fileArr.forEach((fileItem) => {formData.append("files", fileItem.raw);});formData.append("batchId", batchId.value);//整体校验接口 获取文件状态upLoadToHttp(formData).then((resList) => {if (!resList.length) {ElMessage.error("获取文件列表为空");return;}fileArr.forEach((item, index) => {state.fileList.push({...resList[index],...fileArr[index],fileType: item.name.slice(item.name.lastIndexOf(".")),fileName: item.name.slice(0, item.name.lastIndexOf(".")),});});});
}, 300);// 多个文件时上传方法会调用多次 因为配置了手动上传 before-upload不生效
const checkFileSize = (fileArr) => {//文件数量限制if (fileArr.length > 10) {ElMessage.error("上传文件数量最多10个!");return false;}//文件大小限制let allfileSizeNum = fileArr.map((fileItem) => {return fileItem.size;}).reduce(function (prev, curr) {return prev + curr;}, 0);const is20M = allfileSizeNum / 1024 / 1024 < 20;if (!is20M) {ElMessage.error("上传文件总大小不能超过20MB!");return false;}return true;
};