vue+element实现一个excel表格下载的功能

2022-07-17 09:25:13

最近在使用vue-element-admin这个后台管理框架开源模板在做一个管理后台,使用起来其实还挺方便的,大部分的组件源码里面都已经写好了,用的时候只需要把源码拿出来修改修改,也就成了。

这里记录一下开发过程中遇到的一些功能。


资料相关

vue-element-admin

推荐指数:star:55k
Github 地址:https://github.com/PanJiaChen/vue-element-admin
Demo体验:https://panjiachen.github.io/vue-element-admin/#/dashboard

一个基于 vue2.0 和 Eelement 的控制面板 UI 框架,这是使用vue技术栈开发的前端程序员的首选管理系统模板,模板以及非常的成熟了,并且有相关的社区和维护人员,开发时候遇到问题也不要慌。


今天记录一个表格下载的功能

在demo给到的源码里面,可以看到也是有表格下载的功能的,在这个基础上进行一些修改,大概是这个样子,点击下载按钮,将页面上显示的表格下载出来即可。即调用后端给到的接口,直接从后端服务器上下载表格。后端会返回一个二进制文件给到我这边。

参考代码:
index.vue

<template>
  <div class="app-container">
   <el-button  type="primary"  icon="el-icon-download" @click="handleDownload">
        导出基础表格
   </el-button>
  </div>
</template>
<script>
import { exportBaseInfoVIP} from '@/api/exportExcel'
export default {
  data() {
    return { 
      filename: '',
      bookType: 'xlsx'
    };
  },
  computed: {

  },
  methods: {
    downloadExcel(res, fileName = '未命名.xls') {
      debugger;
      const a = document.createElement('a')
      const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
      const url = URL.createObjectURL(blob)
      a.setAttribute('href', url)
      a.setAttribute('download', fileName)
      a.click()
    },
    async handleDownload() {
      const res = await exportBaseInfoVIP()
      this.downloadExcel(res, '会员基础信息.xls')
    },
  }
};
</script>

api

import request from '@/utils/request'
//基础信息
export const exportBaseInfoVIP = () => {
  return request({
    url: '/statistics/childrenUser/export',
    responseType:"blob",
    method: 'get'
  })
}

request.js

if (response.headers['content-type'] === "application/x-msdownload") {
      let disposition = decodeURI(response.headers['content-disposition']);
      let fileName = disposition.split('=')[1];
      const a = document.createElement('a')
      const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
      const url = URL.createObjectURL(blob)
      a.setAttribute('href', url)
      a.setAttribute('download', fileName)
      a.click()
      return
    }

效果如下:
点击按钮,即可下载excel表格

注意:本地可能会出现下载文件名称为undefined的问题,部署在服务器上,即可获得excel文件名称。


  • 作者:祈澈菇凉
  • 原文链接:https://wangxiaoting.blog.csdn.net/article/details/108336961
    更新时间:2022-07-17 09:25:13