基于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
|
9月前
|
JavaScript 前端开发 Java
制造业ERP源码,工厂ERP管理系统,前端框架:Vue,后端框架:SpringBoot
这是一套基于SpringBoot+Vue技术栈开发的ERP企业管理系统,采用Java语言与vscode工具。系统涵盖采购/销售、出入库、生产、品质管理等功能,整合客户与供应商数据,支持在线协同和业务全流程管控。同时提供主数据管理、权限控制、工作流审批、报表自定义及打印、在线报表开发和自定义表单功能,助力企业实现高效自动化管理,并通过UniAPP实现移动端支持,满足多场景应用需求。
885 1
|
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开发的会议预约管理系统
|
6月前
|
前端开发 JavaScript Java
基于springboot+vue开发的校园食堂评价系统【源码+sql+可运行】【50809】
本系统基于SpringBoot与Vue3开发,实现校园食堂评价功能。前台支持用户注册登录、食堂浏览、菜品查看及评价发布;后台提供食堂、菜品与评价管理模块,支持权限控制与数据维护。技术栈涵盖SpringBoot、MyBatisPlus、Vue3、ElementUI等,适配响应式布局,提供完整源码与数据库脚本,可直接运行部署。
367 6
基于springboot+vue开发的校园食堂评价系统【源码+sql+可运行】【50809】
|
7月前
|
Python
Excel中如何批量重命名工作表与将每个工作表导出到单独Excel文件
本文介绍了如何在Excel中使用VBA批量重命名工作表、根据单元格内容修改颜色,以及将工作表导出为独立文件的方法。同时提供了Python实现导出工作表的代码示例,适用于自动化处理Excel文档。
|
9月前
|
供应链 JavaScript BI
ERP系统源码,基于SpringBoot+Vue+ElementUI+UniAPP开发
这是一款专为小微企业打造的 SaaS ERP 管理系统,基于 SpringBoot+Vue+ElementUI+UniAPP 技术栈开发,帮助企业轻松上云。系统覆盖进销存、采购、销售、生产、财务、品质、OA 办公及 CRM 等核心功能,业务流程清晰且操作简便。支持二次开发与商用,提供自定义界面、审批流配置及灵活报表设计,助力企业高效管理与数字化转型。
755 2
ERP系统源码,基于SpringBoot+Vue+ElementUI+UniAPP开发
|
9月前
|
人工智能 算法 安全
使用CodeBuddy实现批量转换PPT、Excel、Word为PDF文件工具
通过 CodeBuddy 实现本地批量转换工具,让复杂的文档处理需求转化为 “需求描述→代码生成→一键运行” 的极简流程,真正实现 “技术为效率服务” 的目标。感兴趣的快来体验下把
505 10
|
12月前
|
文字识别 Serverless 开发工具
【全自动改PDF名】批量OCR识别提取PDF自定义指定区域内容保存到 Excel 以及根据PDF文件内容的标题来批量重命名
学校和教育机构常需处理成绩单、报名表等PDF文件。通过OCR技术,可自动提取学生信息并录入Excel,便于统计分析和存档管理。本文介绍使用阿里云服务实现批量OCR识别、内容提取、重命名及导出表格的完整步骤,包括开通相关服务、编写代码、部署函数计算和设置自动化触发器等。提供Python示例代码和详细操作指南,帮助用户高效处理PDF文件。 链接: - 百度网盘:[链接](https://pan.baidu.com/s/1mWsg7mDZq2pZ8xdKzdn5Hg?pwd=8866) - 腾讯网盘:[链接](https://share.weiyun.com/a77jklXK)
1839 5
|
JavaScript Java 测试技术
基于SpringBoot+Vue实现的留守儿童爱心网站设计与实现(计算机毕设项目实战+源码+文档)
博主是一位全网粉丝超过100万的CSDN特邀作者、博客专家,专注于Java、Python、PHP等技术领域。提供SpringBoot、Vue、HTML、Uniapp、PHP、Python、NodeJS、爬虫、数据可视化等技术服务,涵盖免费选题、功能设计、开题报告、论文辅导、答辩PPT等。系统采用SpringBoot后端框架和Vue前端框架,确保高效开发与良好用户体验。所有代码由博主亲自开发,并提供全程录音录屏讲解服务,保障学习效果。欢迎点赞、收藏、关注、评论,获取更多精品案例源码。
|
4月前
|
JavaScript Java 关系型数据库
基于springboot的项目管理系统
本文探讨项目管理系统在现代企业中的应用与实现,分析其研究背景、意义及现状,阐述基于SSM、Java、MySQL和Vue等技术构建系统的关键方法,展现其在提升管理效率、协同水平与风险管控方面的价值。