VUE element-ui之导入excel模板至后端接口
步骤:
- 按钮外包裹上传组件
<el-upload ref="upload" class="filter-item" action="#" :before-upload="beforeUpload" type="primary" :http-request="uploadOk" :on-change="uploadExcel" :show-file-list="false" :file-list="fileList" :limit="limitUpload" 这里注意!!!:limit为上传个数(如果为1,那么只能上传一次,除二次调用需刷新页面) accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" :auto-upload="false" > <el-button type="primary" size="mini" icon="el-icon-bottom-right">Excel导入</el-button> </el-upload>
组件内属性方法详细介绍可参考这里不再赘述 2.定义所需变量
data() { return { fileList: [], //上传的文件列表, 例如: [{name: food.jpg, url: https://xxx.cdn.com/xxx.jpg}] limitUpload: 100, //允许上传次数(不刷新页面情况下) } }
3.调用方法即可
//上传前校验(其实如果在accept中限制了格式,这一步可有可无---) beforeUpload(file) { // 文件类型 console.log(`上传前校验---`, file) const isType = file.type === application/vnd.ms-excel const isTypeComputer = file.type === application/vnd.openxmlformats-officedocument.spreadsheetml.sheet const fileType = isType || isTypeComputer if (!fileType) { this.$message.error(上传文件只能是xls/xlsx格式!) } // 文件大小限制为2M const fileLimit = file.size / 1024 / 1024 < 2 if (!fileLimit) { this.$message.error(上传文件大小不超过2M!) } return fileType && fileLimit }, // 自定义上传(此方法我打印不出任何数据,注释了也不影响---) uploadOk(param) { // console.log(`上传成功---`, param) // const fileFormData = new FormData() // fileFormData.append(uploadFile, param.file) // console.log(`上传参数---`, param.file) // crudUser.uploadExcel(fileFormData).then(res => { // console.log(`上传成功???---`, res) // }) }, // excel表上传(方法调用在此方法中) uploadExcel(file, fileList) { const fileTemp = file.raw const fileName = file.raw.name const fileType = fileName.substring(fileName.lastIndexOf(.) + 1) // 判断上传文件格式 if (fileTemp) { if ((fileType === xlsx) || (fileType === xls)) { const formData = new FormData() //这一步不能变 formData .append(uploadFile, file.raw) crudUser.uploadExcel(formData ).then(res => { //调用接口,传递参数。 this.crud.refresh() //这里是封装的刷新方法,可以无刷新更新页面数据 this.$message({ message: res,//这里是后端返回的提示文字--- type: success }) }) } else { this.$message({ type: warning, message: 附件格式错误,请重新上传! }) } } else { this.$message({ type: warning, message: 请上传附件! }) } }
以上亲测有效,有不足之处请指出交流,希望能帮到您。 贴两张图:
我这里做的是一整套:下载excel导入模板—>excel导入—>exce导出(下载excel导入模板、导出excel没什么难度,可以参考我之前的博文)