vue实现excel导出模板功能以及excel批量导入功能

1.excel导出模板功能

//导出按钮
<el-button type="text" @click="reportDownload">因子导入模板.xls</el-button>

//API接口
  handleExcel: (data) => request({
    url: '/hbdal/carbon/carbonBase/info/template',
    method: 'post',
    responseType: 'blob', // 表明返回服务器返回的数据类型
    headers: {
      'Content-Type': 'application/json'
    },
    data
  })

// 例如:import 《组件名称》 from '《组件路径》';
import API from '@/api/CBase/factorLibrary'
//导出方法  
  reportDownload() {
      API.handleExcel({}).then(({ data }) => {
        console.log(data)
        const blob = new Blob([data]) // 把得到的结果用流对象转一下
        var a = document.createElement('a') // 创建一个<a></a>标签
        a.href = URL.createObjectURL(blob) // 将流文件写入a标签的href属性值
        a.download = '因子库上传模板.xlsx' // 设置文件名
        a.style.display = 'none' // 障眼法藏起来a标签
        document.body.appendChild(a) // 将a标签追加到文档对象中
        a.click() // 模拟点击了a标签,会触发a标签的href的读取,浏览器就会自动下载了
        a.remove() // 一次性的,用完就删除a标签
      })
    },

2.excel导入功能

//自动上传单个文件 
<el-upload
                  ref="upload"
                  :action="uploadUrl"
                  accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                  :headers="headersup"
                  :max-size="102400"
                  :on-success="uploadSuccess"
                  :on-error="uploadError"
                  :before-upload="uploadBoforeUpload"
                  :show-file-list="false"
                >
                  <el-button slot="trigger" type="primary">导入因子</el-button>
                </el-upload>

//初始化定义的变量数据
 uploadUrl: process.env.VUE_APP_BASE_API + '/wiscarbon/edc/process/data/upload',
      headersup: {
        // 'Content-Type': 'multipart/form-data',
        'Authorization': getToken()
      },

//定义的方法
// 上传成功
    async uploadSuccess() {
      this.$message.success('上传成功')
    },
    uploadBoforeUpload(file) {
      const isLt10k = file.size / 1024 / 1024 < 10
      if (!isLt10k) {
        this.$message.error('上传文件大小不能超过 10M!')
        return false
      }
      this.loading = this.$loading({
        lock: true,
        text: '上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      setTimeout(() => {
        this.loading.close()
      }, 5000)
    },
    uploadError() {
      this.$message.error('上传失败')
      this.loading.close()
    }

猜你喜欢

转载自blog.csdn.net/weixin_53339757/article/details/130252136