vue实现下载EXCEL模板、导入EXCEL文件
在项目中很常见需要先下载模板,根据模板导入
下面展示一些 下载模板代码片段
。
需要有一个下载模板的接口,点击下载触发函数,调用接口,返回下载地址
接口请求数据格式为
Data: "/Template/PRO/car_import.xls"
所以要对数据进行处理,进而封装了一个函数如下
baseURL
在main.js
文件全局注入返回为window.URLGLOBAL.URL
(返回接口域名http://10.11.0.102:9527/
),relativeURL
为返回的接口地址
export function combineURL(baseURL, relativeURL) {
return relativeURL ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL
}
调用接口函数 代码片
如下
handleDownload() {
CarDataTemplate({}).then(res => {
if (res.IsSucceed) {
window.open(combineURL(this.$baseUrl, res.Data), '_blank')
} else {
this.$message({
message: res.Message,
type: 'error'
})
}
})
},
导入
采用elment ui 组件库
<template>
<div class="c-upload-container">
<el-upload
ref="upload"
drag
:limit="limit"
:accept="accept"
:before-upload="beforeUpload"
:auto-upload="autoUpload"
action="string"
>
<svg-icon icon-class="upload-icon" class-name="cs--icon-upload" />
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em>
<div slot="tip" class="el-upload__tip">支持格式: {{ accept }},{{ tip }}</div>
</div>
</el-upload>
<footer class="cs-footer">
<el-button @click="$emit('close')">取 消</el-button>
<el-button type="primary" :loading="btnLoading" @click="handleSubmit">确 定</el-button>
</footer>
</div>
</template>
beforeUpload
函数如下ImportCar
为导入的接口
beforeUpload(file) {
const fileFormData = new FormData()
fileFormData.append('files', file)
this.btnLoading = true
ImportCar(fileFormData).then(res => {
if (res.IsSucceed) {
this.btnLoading = false
this.$message({
message: '导入成功',
type: 'success'
})
this.$emit('refresh')
this.$emit('close')
} else {
this.$message({
message: res.Message,
type: 'error'
})
this.btnLoading = false
}
})
},
提交时 handleSubmit
调用接口。
handleSubmit() {
this.$refs.upload.submit()
}
取消按钮调用父组件函数关闭弹窗
Close() {
this.dialogVisible = false
}