基于SpringBoot + EasyExcel + Vue + Blob实现导出Excel文件的前后端完整过程

这篇具有很好参考价值的文章主要介绍了基于SpringBoot + EasyExcel + Vue + Blob实现导出Excel文件的前后端完整过程。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

首先前端发起HTTP请求之后,后端返回一个Excel输出流,然后前端用Blob类型接收数据,并且解析响应头数据以及提取源文件名,最后用a标签完成下载。

一、后端代码

(1)导入阿里巴巴的EasyExcel依赖(pom.xml)

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.3.1</version>
</dependency>

(2)控制层(GameController.java)

@CrossOrigin
@RequestMapping(value = "exportFile", method = RequestMethod.GET)
@ResponseBody
public void exportFile(@RequestParam("operator") String operator, HttpServletResponse response) throws IOException {
    gameService.exportFile(operator, response);
}

(3)接口层(IGameService.java)

void exportFile(String operator, HttpServletResponse response) throws IOException;

(4)实现层(GameServiceImpl.java)

/**
 * 王者Excel实体
 * 说明:this$0特指该内部类所在的外部类的引用,不需要手动定义,编译时自动加上
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
static class KingExcelEntity {
    @ExcelProperty(value = "英雄", index = 0)
    private String hero;

    @ExcelProperty(value = "等级", index = 1)
    private String level;

    @ExcelProperty(value = "金币", index = 2)
    private String gold;

    @ExcelProperty(value = "击杀", index = 3)
    private String kill;

    @ExcelProperty(value = "被击杀", index = 4)
    private String beKilled;

    @ExcelProperty(value = "助攻", index = 5)
    private String assists;

    @ExcelProperty(value = "评分", index = 6)
    private String score;

    @ExcelProperty(value = "是否MVP", index = 7)
    private String mvp;
}

@Override
public void exportFile(String operator, HttpServletResponse response) throws IOException {
    List<KingExcelEntity> KingsList = new ArrayList<>();
    KingsList.add(new KingExcelEntity("云缨", "15", "20013", "21", "5", "16", "12.9", "True"));
    KingsList.add(new KingExcelEntity("王昭君", "15", "17336", "2", "6", "20", "7.5", "False"));
    KingsList.add(new KingExcelEntity("狄仁杰", "15", "16477", "9", "8", "22", "8.4", "False"));
    KingsList.add(new KingExcelEntity("兰陵王", "15", "16154", "21", "5", "16", "8.6", "False"));
    KingsList.add(new KingExcelEntity("赵怀真", "15", "17414", "6", "6", "21", "10.2", "False"));
    try {
        String fileName = URLEncoder.encode(operator + "-" + "王者荣耀战绩" + ".xlsx", "utf-8");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        EasyExcel.write(response.getOutputStream(), KingExcelEntity.class)
                .sheet("第一页")
                .doWrite(KingsList);
    } catch (Exception e) {
        response.reset();
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        HashMap<String, Object> map = new HashMap<>();
        map.put("status", false);
        map.put("msg", e.getMessage());
        response.getWriter().println(JSONObject.toJSONString(map));
    }
}

二、前端代码

(1)视图页面(/src/view/Example/DownloadBlobFile/index.vue)

<template>
  <div style="padding: 100px">
    <el-button size="small" type="primary" plain @click="handleDownloadBlobFile()">
      <el-icon :size="18">
        <Download />
      </el-icon>
      <span>下载文件</span>
    </el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // ...
    }
  },
  methods: {
    /**
     * 下载Blob文件句柄方法
     */
    handleDownloadBlobFile(evt) {
      const operator = '帅龍之龍' // 操作人员

      this.$axios.get(
        `/api/exportFile`,
        {
          params: {
            'operator': operator
          },
          headers: {
            'Access-Control-Allow-Origin': '*',
            'Auth-Token': '5201314'
          },
          responseType: 'blob'
        }
      )
      .then((res) => {
        try {
          console.log('响应信息 =>', res)

          if (res.data.size > 0) {
            // 响应头信息
            const headers = res.headers

            // attachment;filename=%E5%B8%85%E9%BE%8D%E4%B9%8B%E9%BE%8D-%E7%8E%8B%E8%80%85%E8%8D%A3%E8%80%80%E6%88%98%E7%BB%A9.xlsx
            const contentDisposition = headers['content-disposition']
            console.log('contentDisposition =>', contentDisposition)

            // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8
            const contentType = headers['content-type']
            console.log('contentType =>', contentType)
            
            let fileName = contentDisposition.split(`=`)[1]
            console.log('解析前文件名 =>', fileName) // 解析前文件名:%E5%B8%85%E9%BE%8D%E4%B9%8B%E9%BE%8D-%E7%8E%8B%E8%80%85%E8%8D%A3%E8%80%80%E6%88%98%E7%BB%A9.xlsx

            fileName = decodeURIComponent(fileName)
            console.log('解析后文件名 =>', fileName) // 解析后文件名:帅龍之龍-王者荣耀战绩.xlsx

            this.exportFileToExcel(contentType, res.data, fileName)
          } else {
            this.$message({ message: '文件数据为空', type: 'error', duration: 1000 })
          }
        } catch (e) {
          console.error(e)
          this.$message({ message: e, type: 'error', duration: 1000 })
        }
      })
      .catch((e) => { 
        console.error(e)
        this.$message({ message: e, type: 'error', duration: 1000 })
      })
    },

    /**
     * 导出Excel文件
     */
    exportFileToExcel(contentType, data, fileName) {
      const url = window.URL.createObjectURL(
        new Blob(
          [data],
          {
            type: contentType
          }
        )
      )
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', `${fileName}` || 'template.xlsx')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
  },
};
</script>

三、效果如下 ~

基于SpringBoot + EasyExcel + Vue + Blob实现导出Excel文件的前后端完整过程,# SpringBoot,# Vue,前端,后端

 文章来源地址https://www.toymoban.com/news/detail-602070.html

到了这里,关于基于SpringBoot + EasyExcel + Vue + Blob实现导出Excel文件的前后端完整过程的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringBoot 集成 EasyExcel 3.x 优雅实现 Excel 导入导出

    EasyExcel 是一个基于 Java 的、快速、简洁、解决大文件内存溢出的 Excel 处理工具。它能让你在不用考虑性能、内存的等因素的情况下,快速完成 Excel 的读、写等功能。 EasyExcel文档地址: https://easyexcel.opensource.alibaba.com/ 引入依赖 简单导出 以导出用户信息为例,接下来手把手教

    2024年02月15日
    浏览(28)
  • SpringBoot整合Easyexcel实现将数据导出为Excel表格的功能

    本文主要介绍基于SpringBoot +MyBatis-Plus+Easyexcel+Vue实现缺陷跟踪系统中导出缺陷数据的功能,实现效果如下图: EasyExcel是一个基于Java的、快速、简洁、解决大文件内存溢出的Excel处理工具。他能让你在不用考虑性能、内存的等因素的情况下,快速完成Excel的读、写等功能。 本文

    2024年02月14日
    浏览(31)
  • 使用POI和EasyExcel来实现excel文件的导入导出

    废话不多说咱们直接上干货!!!! 一.读取Excel表格 【1】使用POI读取excel表格中的数据 POI还可以操作我们这个word文档等等,他不仅仅只能弄Excel,而JXI只能操作excel 1.POI的结构,我们可以更具文件的类去选择 相关的对象我当前是使用的XLSX来操作的 HSSF - 提供读写Microsoft

    2024年02月05日
    浏览(36)
  • SpringBoot整合easyExcel实现CSV格式文件的导入导出

    目录 一:pom依赖 二:检查CSV内容格式的工具类 三:Web端进行测试 四:拓展使用 使用hutool工具类来进行导出功能

    2024年02月02日
    浏览(32)
  • 【EasyExcel】在SpringBoot+VUE项目中引入EasyExcel实现对数据的导出(封装工具类)

    一、引入EasyExcel 通过maven引入,坐标如下: 二、后端代码演示 下面以权限系统中的角色列表为案例,演示如何导出数据 实体类 工具类 通过@Component把工具类交给spring管理,在需要使用的地方使用@Resource注入即可 将泛型设置为 \\\" ? \\\",来表示任意类型,可以通过这一个方法完成

    2024年02月16日
    浏览(38)
  • EasyExcel导出Excel文件

    方法一 导入EasyExcel依赖 创建实体类 OrderServiceImpl 如果希望多个sheet导出那么可以 测试类 方法二 导入EasyExcel依赖 编写ExcelUtil 编写Service层代码 controller层代码 方法一与方法二都使用了EasyExcel进行Excel的导出,区别在于方法一建立了实体类进行Excel的导出,这样的好处是可以直

    2024年02月14日
    浏览(25)
  • SpringBoot整合EasyExcel,Excel导入导出就靠它了

    作者主页 :Designer 小郑 作者简介 :3年JAVA全栈开发经验,专注JAVA技术、系统定制、远程指导,致力于企业数字化转型,CSDN学院、蓝桥云课认证讲师。 主打方向 :Vue、SpringBoot、微信小程序 本文讲解了如何在SpringBoot项目中整合EasyExcel,实现Excel快捷导入导出,解析Excel导入导

    2024年02月16日
    浏览(21)
  • 【JAVA】easyexcel 导出excel文件带多个图片

    最终效果  pom版本 实现代码  

    2024年02月16日
    浏览(26)
  • 【Java结合EasyExcel,模板文件填充并导出Excel】

    需求描述: 客户网页上填一个Excel表格,数据存到数据库,这个导出接口要做的就是从数据库中的获取数据并填充到模板文件,最后通过response返给前端一个下载链接,用户即可获取填充好的Excel文件。 方案一: 一开始使用的是easypoi,发现当填充一行数据时是OK的,但是如果

    2024年02月09日
    浏览(39)
  • easyexcel根据模板导出Excel文件,表格自动填充问题

    同事在做easyexcel导出Excel,根据模板导出的时候,发现导出的表格,总会覆盖落款的内容。 这就很尴尬了,表格居然不能自动填充,直接怒喷工具,哈哈。 然后一起看了一下这个问题。 我找了自己的系统中关于表格导出的页面,导出了一下,发现可以正常扩充。 于是排查问

    2024年02月06日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包