vue实现excel表格下载

淩亂°似流年 2022-12-20 12:55 356阅读 0赞

最近在使用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

  1. <template>
  2. <div class="app-container">
  3. <el-button type="primary" icon="el-icon-download" @click="handleDownload">
  4. 导出基础表格
  5. </el-button>
  6. </div>
  7. </template>
  8. <script>
  9. import { exportBaseInfoVIP} from '@/api/exportExcel'
  10. export default {
  11. data() {
  12. return {
  13. filename: '',
  14. bookType: 'xlsx'
  15. };
  16. },
  17. computed: {
  18. },
  19. methods: {
  20. downloadExcel(res, fileName = '未命名.xls') {
  21. debugger;
  22. const a = document.createElement('a')
  23. const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
  24. const url = URL.createObjectURL(blob)
  25. a.setAttribute('href', url)
  26. a.setAttribute('download', fileName)
  27. a.click()
  28. },
  29. async handleDownload() {
  30. const res = await exportBaseInfoVIP()
  31. this.downloadExcel(res, '会员基础信息.xls')
  32. },
  33. }
  34. };
  35. </script>

api

  1. import request from '@/utils/request'
  2. //基础信息
  3. export const exportBaseInfoVIP = () => {
  4. return request({
  5. url: '/statistics/childrenUser/export',
  6. responseType:"blob",
  7. method: 'get'
  8. })
  9. }

request.js
88306c29558ec37b991c51d2c6387924.png

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

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

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

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,356人围观)

还没有评论,来说两句吧...

相关阅读

    相关 vue实现excel表格下载

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