文章目录
关于导入导出excel
导入:本质就是导入一个xls或者xlsx文件,使用elementpluse的el-upload组件,根据前后端协商好的接口,对el-upload的配置项进行配置就可以了。
导出:导出其实有两种做法,一种是获取到数据后前端自行处理,另一种是通过接口后端处理,这里只介绍通过接口后端处理的方法。
一、导入
1.导入组件
<el-upload
class="materialExport"
:action="importURL"
:on-error="uploadFalse"
:on-success="uploadSuccess"
:before-upload="beforeAvatarUpload"
:show-file-list="false"
accept=".xlsx,.xls"
:headers="headerObj"
>
<el-button type="primary">导入</el-button>
</el-upload>
2.配置项
action: 导入的URL
// 导入URL
const importURL = computed(() => {
return `${import.meta.env.VITE_BASE_URL}/aa/bb`
})
before-upload: 导入前的操作(限制文件类型和大小)
// 导入前
function beforeAvatarUpload(file) {
const extension = file.name.split('.')[1] === 'xls'
const extension2 = file.name.split('.')[1] === 'xlsx'
const isLt10M = file.size / 1024 / 1024 < 10
if (!extension && !extension2) {
ElMessage({
message: '上传模板只能是 xls、xlsx格式!',
type: 'error',
})
}
if (!isLt10M) {
console.log('上传模板大小不能超过 10MB!')
ElMessage({
message: '上传模板大小不能超过 10MB!',
type: 'error',
})
}
return extension || extension2 || isLt10M
}
on-success: 导入成功的操作(弹出成功或错误提示)
// 导入成功
function uploadSuccess(response, file, fileList) {
if (response.code == 200) {
ElNotification({
title: 'success',
message: '上传成功',
type: 'success',
})
getTableData()
} else {
ElNotification({
title: 'Error',
message: '上传失败,请检查格式和数据是否正确',
type: 'error',
})
}
console.log(response)
}
headers: 自定义请求头(由于我的后端接口带了token,需要将token加入请求头)
//请求头TOKEN
const headerObj = computed(() => {
return { Authorization: `Bearer ${getToken()}` }
})
二、导出
1.导出按钮
<el-button type="primary" @click="exportData()">导出</el-button>
2.导出方法
// 导出URL
const exportURL = computed(() => {
return `${import.meta.env.VITE_BASE_URL}/aa/bb`
})
// 导出
function exportData() {
axios({
// 用axios发送get请求
method: 'get',
url: exportURL.value, // 请求地址
responseType: 'blob', // 表明返回服务器返回的数据类型
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${getToken()}`,
},
params: {
page: 1,
page_size: 10,
},
}).then((res) => {
// 处理返回的文件流
// new Blob([res])中不加data就会返回下图中[objece objece]内容(少取一层)
const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
const fileName = '物料表.xls' // 下载文件名称
const elink = document.createElement('a')
elink.download = fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放URL 对象
document.body.removeChild(elink)
})
}