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

简介: 本文展示了基于SpringBoot + EasyExcel + Vue + Blob实现导出Excel文件的完整过程,包括后端使用EasyExcel生成Excel文件流,前端通过Blob对象接收并触发下载的操作步骤和代码示例。

首先前端发起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>

三、效果如下 ~

目录
相关文章
|
10月前
|
前端开发 Java 关系型数据库
基于Java+Springboot+Vue开发的鲜花商城管理系统源码+运行
基于Java+Springboot+Vue开发的鲜花商城管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的鲜花商城管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。技术学习共同进步
627 7
|
5月前
|
前端开发 安全 Java
基于springboot+vue开发的会议预约管理系统
一个完整的会议预约管理系统,包含前端用户界面、管理后台和后端API服务。 ### 后端 - **框架**: Spring Boot 2.7.18 - **数据库**: MySQL 5.6+ - **ORM**: MyBatis Plus 3.5.3.1 - **安全**: Spring Security + JWT - **Java版本**: Java 11 ### 前端 - **框架**: Vue 3.3.4 - **UI组件**: Element Plus 2.3.8 - **构建工具**: Vite 4.4.5 - **状态管理**: Pinia 2.1.6 - **HTTP客户端
710 4
基于springboot+vue开发的会议预约管理系统
|
11月前
|
XML Java Maven
springboot-多环境配置文件
本文介绍了如何创建开发和生产环境的配置文件,并在IDEA和Maven中进行配置。开发环境中,通过设置profile为`dev`来指定配置文件;生产环境中,使用Maven命令参数`-Pprod`打包并指定配置文件。公共配置可放在`application.yml`中统一管理。日志配置需确保`logback-spring.xml`中的profile正确,以保证日志正常输出。
876 4
springboot-多环境配置文件
|
6月前
|
前端开发 JavaScript Java
基于springboot+vue开发的校园食堂评价系统【源码+sql+可运行】【50809】
本系统基于SpringBoot与Vue3开发,实现校园食堂评价功能。前台支持用户注册登录、食堂浏览、菜品查看及评价发布;后台提供食堂、菜品与评价管理模块,支持权限控制与数据维护。技术栈涵盖SpringBoot、MyBatisPlus、Vue3、ElementUI等,适配响应式布局,提供完整源码与数据库脚本,可直接运行部署。
367 6
基于springboot+vue开发的校园食堂评价系统【源码+sql+可运行】【50809】
|
存储 前端开发 Java
Springboot静态资源映射及文件映射
在Spring Boot项目中,为了解决前端访问后端存储的图片问题,起初尝试通过静态资源映射实现,但发现这种方式仅能访问打包时已存在的文件。对于动态上传的图片(如头像),需采用资源映射配置,将特定路径映射到服务器上的文件夹,确保新上传的图片能即时访问。例如,通过`addResourceHandler(&quot;/img/**&quot;).addResourceLocations(&quot;file:E:\\myProject\\forum_server\\&quot;)`配置,使前端可通过URL直接访问图片。
781 0
Springboot静态资源映射及文件映射
|
8月前
|
监控 数据可视化 JavaScript
springboot + vue的MES系统生产计划管理源码
MES系统(制造执行系统)的生产计划管理功能是其核心模块之一,涵盖生产计划制定与优化、调度排程、进度监控反馈、资源管理调配及可视化报告五大方面。系统基于SpringBoot + Vue-Element-Plus-Admin技术栈开发,支持多端应用(App、小程序、H5、后台)。通过实时数据采集与分析,MES助力企业优化生产流程,适用于现代化智能制造场景。
417 1
|
9月前
|
供应链 JavaScript BI
ERP系统源码,基于SpringBoot+Vue+ElementUI+UniAPP开发
这是一款专为小微企业打造的 SaaS ERP 管理系统,基于 SpringBoot+Vue+ElementUI+UniAPP 技术栈开发,帮助企业轻松上云。系统覆盖进销存、采购、销售、生产、财务、品质、OA 办公及 CRM 等核心功能,业务流程清晰且操作简便。支持二次开发与商用,提供自定义界面、审批流配置及灵活报表设计,助力企业高效管理与数字化转型。
755 2
ERP系统源码,基于SpringBoot+Vue+ElementUI+UniAPP开发
|
11月前
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
|
JavaScript Java 测试技术
基于SpringBoot+Vue实现的留守儿童爱心网站设计与实现(计算机毕设项目实战+源码+文档)
博主是一位全网粉丝超过100万的CSDN特邀作者、博客专家,专注于Java、Python、PHP等技术领域。提供SpringBoot、Vue、HTML、Uniapp、PHP、Python、NodeJS、爬虫、数据可视化等技术服务,涵盖免费选题、功能设计、开题报告、论文辅导、答辩PPT等。系统采用SpringBoot后端框架和Vue前端框架,确保高效开发与良好用户体验。所有代码由博主亲自开发,并提供全程录音录屏讲解服务,保障学习效果。欢迎点赞、收藏、关注、评论,获取更多精品案例源码。
|
JavaScript Java 测试技术
基于SpringBoot+Vue实现的家政服务管理平台设计与实现(计算机毕设项目实战+源码+文档)
面向大学生毕业选题、开题、任务书、程序设计开发、论文辅导提供一站式服务。主要服务:程序设计开发、代码修改、成品部署、支持定制、论文辅导,助力毕设!