系统中经常会遇到要实现批量导入/导出
数据的功能,导入就需要先下载一个模板,然后在模板文件中填写内容,最后导入模板,导出就可能是下载一个excel文件。
1、导出
新建一个export.js
文件如下:
import {MessageBox,Message,Notification
} from 'element-ui'
import axios from 'axios'
// 导出
export function outExcel(name, url, data, info) {const that = this;MessageBox.confirm(name, "提示", {type: "warning"}).then(async () => {Notification.info({title: '提示',message: '正在导出,请稍后 <i class="el-icon-loading" style="font-size:20px"></i>',dangerouslyUseHTMLString: true,position: 'bottom-left',duration: 0})const time = data;let formData = new FormData();if (time != null) {for (var p in time) {formData.append(p, time[p]);}}axios({method: "post",url: process.env.VUE_APP_BASE_API + url,data: formData,headers: {Authorization: "token " + 'XXX'.,"Content-Type": "multipart/form-data"},responseType: "blob"}).then(data => {if (data.data.type === "application/json") {var reader = new FileReader();reader.onloadend = function () {let res = JSON.parse(reader.result);if (res && res.msg) {Message.warning(res.msg + "," + res.data);setTimeout(() => {Notification.closeAll()}, 1000);}};reader.readAsText(data.data);return;}let url = window.URL.createObjectURL(new Blob([data.data]));let link = document.createElement("a");link.style.display = "none";link.href = url;link.setAttribute("download", info);document.body.appendChild(link);link.click();if (info.indexOf('模板') !== -1) {Message.success('模板下载成功')setTimeout(() => {Notification.closeAll()}, 1000);} else {Notification.closeAll()Notification.success({title: '提示',message: '导出成功',position: 'bottom-left',duration: 2000})setTimeout(() => {Notification.closeAll()}, 2000);}}).catch(data => {if (info.indexOf('模板') !== -1) {Message.error('模板下载失败')} else {Message.error('导出失败')}});}).catch(() => {return false;});
}
可接收参数有: name
(提示语),url
(接口路径),data
(接口参数),info
(文件名)
需要将传入的 data
对象转换为 FormData
对象,用于发送POST请求
的数据,同时设置请求头包括Authorization
信息和Content-Type
为multipart/form-data
,以及指定响应类型为blob
。请求成功的回调函数,判断响应的数据类型,如果是JSON格式
,则使用FileReader
来读取文件内容,解析其中的消息并显示警告信息,然后关闭所有通知,并返回。如果不是JSON格式,则将响应的数据转换为URL
,创建一个隐藏的链接并设置下载属性,然后模拟点击下载
。
使用时先引入文件中的方法直接调用
exportTemplate () {outExcel('请确认是否需要下载信息模板',"user/downloadExample",{},"人员信息模板.xls");
},
2、导入
使用el-upload
组件,参数有: action
(必选参数,上传的地址),headers
(设置上传的请求头部),multiple
(是否支持多选文件),data
(附带的额外参数),name
(文件字段名),file-list
(上传的文件列表),limit
(最大允许上传个数),详情参考Element
官方文档。
<template><div><el-upload style="display: inline-block; margin: 0 10px" ref="upload" :show-file-list='false' :headers="headers" :action="action" :on-success="handleSuccess" :on-error="hadleError" :limit="1" :file-list="fileList"><el-button type="primary"><img class="img" src="@/assets/image/xinxi2.png" alt=""> 导入</el-button></el-upload></div>
</template><script>
export default {data () {return {fileList: [],action:process.env.VUE_APP_BASE_API + "user/importData",headers: {Authorization:"token " + 'XXX'},}},methods: {// 上传成功handleSuccess (response, file, fileList) {this.$refs.upload.clearFiles();if (fileList[0].response.code === 1) {this.fileList = [];this.$message.success("上传成功!!!");} else {this.fileList = [];this.$message.error(fileList[0].response.msg);}},// 上传失败hadleError (err, file, fileList) {console.log(error)this.$refs.upload.clearFiles();this.fileList = [];const result = JSON.parse(error.message);this.$message.error(result.msg);},}
}
</script>