基于SpringBoot的后端导出Excel文件

后端导出Excel,前端下载。

系列文章指路👉

系列文章-基于SpringBoot3创建项目并配置常用的工具和一些常用的类

文章目录

  • 后端导出Excel
    • 引入依赖
    • 写入响应
  • 前端下载
    • 后端导出失败和成功返回的内容类型不同,因此需要分别判断。
  • 工具类
    • ServletUtils.java
    • FileUtils.java
    • file.js

后端导出Excel

引入依赖

poi 操作xls,doc…;poi-ooxml操作xlsx,docx…
⚠️使用的版本比较新,可能跟老版本有些写法不兼容

        <!-- poi and poi-ooxml --><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>5.2.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>5.2.2</version></dependency>

写入响应

  • 生成Workbook对象这一步应该是个性化的。
  • 中文的文件名需要经过编码,不然传到前端会乱码
  • 工具类的源码放在文末
    public Object export(String orderNum) {// 1. 生成Excel Workbook对象XSSFWorkbook workbook = initWorkbook(orderNum);HttpServletResponse rep = ServletUtils.getResponse();String errMessage;String fileName = "超市购进单-"+ DateUtil.today() + ".xlsx";if(Objects.isNull(rep)){throw new NullPointerException("HttpServletResponse 为空");}try {// 2. 将HSSFWorkbook文件写入到响应输出流中,供前端下载FileUtils.writeToResponse(workbook, fileName, rep);return null;}catch (IOException ioe){log.error("OrderServiceImpl export --- 导出过程中遇到输入输出异常: {}" ,ioe.toString());errMessage = "导出过程中遇到输入输出异常" + ioe;} catch (Exception e){log.error("OrderServiceImpl export --- 导出过程中遇到其他异常: {}" ,e.toString());errMessage = "导出过程中遇到其他异常:" + e;}return BaseResult.fail(errMessage);}

前端下载

后端导出失败和成功返回的内容类型不同,因此需要分别判断。

  • 返回的是json类型的错误信息:
    res1
  • 只有导出成功,才是文件流:res2
<template><h1>Excel导出测试</h1><p style="margin-top: 40px"><a-space><a-button type="primary" :icon="h(DownloadOutlined)" @click="downloadFile">下载Excel</a-button></a-space></p>
</template>
<script setup>
import {h} from 'vue';
import {DownloadOutlined} from '@ant-design/icons-vue';
import {UploadOutlined} from '@ant-design/icons-vue';
import {message} from "ant-design-vue";
import http from "@/utils/axios/index.js";
import {downloadFile as downer} from "@/utils/file.js";function downloadFile() {http.get('/manage/order/export', {params: {orderNum: '000001'},responseType: 'blob'}).then(resp => {if (resp.data.type === 'application/json') {// 失败了才会返回json类型const reader = new FileReader();reader.readAsText(resp.data, 'utf-8');reader.onload = () => {const result = JSON.parse(reader.result)message.error(`Error: ${result.message}`);};} else {downer(resp)}}).catch(err => {message.error('导出失败:' + err)console.log(err)})
}
</script>

工具类

ServletUtils.java

package com.ya.boottest.utils.servlet;import com.alibaba.fastjson.JSON;
import com.ya.boottest.utils.result.BaseResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import java.io.IOException;
import java.util.Objects;/*** <p>* Servlet 工具类* </p>** @author Ya Shi* @since 2024/1/4 14:29*/@Slf4j
public class ServletUtils {/*** 获取Attributes** @return ServletRequestAttributes*/public static ServletRequestAttributes getRequestAttributes() {RequestAttributes attributes = RequestContextHolder.getRequestAttributes();if(Objects.isNull(attributes)){log.error("ServletUtils 获取到的RequestAttributes为空");throw new RuntimeException("ServletUtils 获取到的RequestAttributes为空");}return (ServletRequestAttributes) attributes;}/*** 获取request** @return HttpServletRequest*/public static HttpServletRequest getRequest() {return getRequestAttributes().getRequest();}/*** 获取session** @return HttpSession*/public static HttpSession getSession() {return getRequest().getSession();}/*** 获取response** @return HttpServletResponse*/public static HttpServletResponse getResponse() {return getRequestAttributes().getResponse();}   
}

FileUtils.java

package com.ya.boottest.utils.file;import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;/*** <p>*  文件util* </p>** @author Ya Shi* @since 2023/8/11 11:58*/
@Slf4j
public class FileUtils {/*** 将HSSFWorkbook文件写入到响应输出流中,供前端下载* @param workbook 文件对象* @param fileName 文件名* @param response HttpServletResponse响应* @throws IOException IO异常*/public static void writeToResponse(XSSFWorkbook workbook, String fileName, HttpServletResponse response) throws IOException{try {response.setHeader("Content-Disposition", "attachment;filename=" + processFileName(fileName));response.setContentType("application/octet-stream; charset=utf-8");response.setCharacterEncoding("utf-8");ByteArrayOutputStream bos = new ByteArrayOutputStream();workbook.write(bos);byte[] bytes = bos.toByteArray();OutputStream outData = response.getOutputStream();outData.write(bytes);outData.flush();} catch (IOException e) {log.error("FileUtil writeToResponse workbook写入响应失败-----> " + e);throw e;}}/*** 对要下载的文件的名称进行编码,防止中文乱码问题。** @param fileName 文件名* @return String*/public static String processFileName(String fileName) throws IOException {String codedFilename;String prefix = fileName.lastIndexOf(".") != -1 ? fileName.substring(0, fileName.lastIndexOf(".")) : fileName;String extension = fileName.lastIndexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".")) : "";String name = java.net.URLEncoder.encode(prefix, StandardCharsets.UTF_8);if (name.lastIndexOf("%0A") != -1) {name = name.substring(0, name.length() - 3);}int limit = 150 - extension.length();if (name.length() > limit) {name = java.net.URLEncoder.encode(prefix.substring(0, Math.min(prefix.length(), limit / 9)), StandardCharsets.UTF_8);if (name.lastIndexOf("%0A") != -1) {name = name.substring(0, name.length() - 3);}}name = name.replaceAll("[+]", "%20");codedFilename = name + extension;log.info("FileUtil processFileName codedFilename-----> " + codedFilename);return codedFilename;}
}

file.js

export function downloadFile(resp) {const tmp = 'filename='const contentDisposition = decodeURIComponent(resp.headers['content-disposition'])const fileName = contentDisposition.substring(contentDisposition.indexOf(tmp) + tmp.length)const contentType = resp.headers['content-type']const blob = new Blob([resp.data], {type: contentType})let a = document.createElement('a')a.href = URL.createObjectURL(blob)a.download = fileNamea.target = '_blank'a.style.display = 'none'document.body.appendChild(a)a.click()a.remove()
}

明月别枝惊鹊,清风半夜鸣蝉。

—— 宋朝 · 辛弃疾《 西江月 夜行黄沙道中 》

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/668961.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

GLIP:零样本学习 + 目标检测 + 视觉语言大模型

GLIP 核心思想GLIP 对比 BLIP、BLIP-2、CLIP 主要问题: 如何构建一个能够在不同任务和领域中以零样本或少样本方式无缝迁移的预训练模型&#xff1f;统一的短语定位损失语言意识的深度融合预训练数据类型的结合语义丰富数据的扩展零样本和少样本迁移学习 效果 论文&#xff1a;…

docker核心技术

一. 从系统架构谈起 传统分层架构 vs 微服务 微服务改造 分离微服务的方法建议: 审视并发现可以分离的业务逻辑业务逻辑,在对业务领域不是特别熟悉的时候,按照部门职能进行划分,例如账号、财务等寻找天生隔离的代码模块,可以借助于静态代码分析工具如果可以闭环的解决一…

SQL Server之DML触发器

一、如何创建一个触发器呢 触发器的定义语言如下&#xff1a; CREATE [ OR ALTER ] TRIGGER trigger_nameon {table_name | view_name}{for | After | Instead of }[ insert, update,delete ]assql_statement从这个定义语言我们可以知道如下信息&#xff1a; trigger_name&…

从领域外到领域内:LLM在Text-to-SQL任务中的演进之路

导语 本文介绍了ODIS框架&#xff0c;这是一种新颖的Text-to-SQL方法&#xff0c;它结合了领域外示例和合成生成的领域内示例&#xff0c;以提升大型语言模型在In-context Learning中的性能。 标题&#xff1a;Selective Demonstrations for Cross-domain Text-to-SQL会议&am…

计算机组成原理 — 存储器(1)

存储器 大家好呀&#xff01;我是小笙&#xff0c;由于存储器这部分章节内容较多&#xff0c;我分成二部分进行总结&#xff0c;以下是第一部分&#xff0c;希望内容对你有所帮助&#xff01; 概述 存储器是计算机系统中的记忆设备&#xff0c;用来存放程序和数据 存储器分…

vue3 mathjax 数学公式

安装 pnpm install mathjax 新建文件/util/mathjax.js window.MathJax {tex: {inlineMath: [["$", "$"],["\\(", "\\)"],], // 行内公式选择符displayMath: [["$$", "$$"],["\\[", "\\]"…

UE4运用C++和框架开发坦克大战教程笔记(十七)(第51~54集)

UE4运用C和框架开发坦克大战教程笔记&#xff08;十七&#xff09;&#xff08;第51~54集&#xff09; 51. UI 框架介绍UE4 使用 UI 所面临的问题以及解决思路关于即将编写的 UI 框架的思维导图 52. 管理类与面板类53. 预加载与直接加载54. UI 首次进入界面 51. UI 框架介绍 U…

《合成孔径雷达成像算法与实现》Figure6.4

clc clear close all参数设置 距离向参数设置 R_eta_c 20e3; % 景中心斜距 Tr 2.5e-6; % 发射脉冲时宽 Kr 20e12; % 距离向调频率 alpha_os_r 1.2; % 距离过采样率 Nrg 320; % 距离线采样数 距离向…

CSS布局

CSS布局 1. 版心 在 PC 端网页中&#xff0c;一般都会有一个固定宽度且水平居中的盒子&#xff0c;来显示网页的主要内容&#xff0c;这是网页的版心。版心的宽度一般是 960 ~ 1200 像素之间。版心可以是一个&#xff0c;也可以是多个。 2. 常用布局名词 3. 重置默认样式 很…

C#验证字符串的长度,用正则表达式 vs 字符数组长度或字符串的长度

目录 一、使用的方法 1.使用正则表达式 2.通过计算字符串的长度验证 二、实例 1.源码 2.生成效果 一、使用的方法 1.使用正则表达式 使用正则表达式可以判断和限制用户输入的字符串长度。 比如验证用户密码不得少于8为&#xff0c;匹配的正则表达式"^.{8,}$"…

AIGC专题:AIGC教育行业全景报告

今天分享的是AI GC系列深度研究报告&#xff1a;《AIGC专题&#xff1a;AIGC教育行业全景报告》。 &#xff08;报告出品方&#xff1a;量子位智库&#xff09; 报告共计&#xff1a;31页 生成式AI快速落地教育&#xff0c;技术推动教育理念实施 生成式AI将我们带入AI2.0时代…

数据类型完整版

第三章 数据类型 3.1 Key操作 3.1.1 相关命令 序号命令语法描述1DEL key该命令用于在 key 存在时删除 key2DUMP key序列化给定 key &#xff0c;并返回被序列化的值3EXISTS key检查给定 key 是否存在&#xff0c;存在返回1&#xff0c;否则返回04EXPIRE key seconds为给定 k…

MacOS系统电脑远程桌面控制windows系统电脑【内网穿透】

最近&#xff0c;我发现了一个超级强大的人工智能学习网站。它以通俗易懂的方式呈现复杂的概念&#xff0c;而且内容风趣幽默。我觉得它对大家可能会有所帮助&#xff0c;所以我在此分享。点击这里跳转到网站。 文章目录 1. 测试本地局域网内远程控制1.1 Windows打开远程桌面1…

回归预测 | Matlab实现WOA-CNN-LSTM-Attention鲸鱼算法优化卷积长短期记忆网络注意力多变量回归预测(SE注意力机制)

回归预测 | Matlab实现WOA-CNN-LSTM-Attention鲸鱼算法优化卷积长短期记忆网络注意力多变量回归预测&#xff08;SE注意力机制&#xff09; 目录 回归预测 | Matlab实现WOA-CNN-LSTM-Attention鲸鱼算法优化卷积长短期记忆网络注意力多变量回归预测&#xff08;SE注意力机制&…

问题:0xc8前面加(byte) #人工智能#学习方法的原因是因为0xc8大于??????????? 。 #微信#其他#微信

问题&#xff1a;0xc8前面加&#xff08;byte&#xff09;的原因是因为0xc8大于??????????? 。 参考答案如图所示

大数据学习之Redis,十大数据类型的具体应用(五)

目录 3.9 Redis地理空间&#xff08;GEO&#xff09; 简介 原理 Redis在3.2版本以后增加了地理位置的处理哦 命令 命令实操 如何获得某个地址的经纬度 3.9 Redis地理空间&#xff08;GEO&#xff09; 简介 移动互联网时代LBS应用越来越多&#xff0c;交友软件中附近的…

双非本科准备秋招(10.2)—— JVM3:垃圾收集器

垃圾收集器 分为七种&#xff0c;如下&#xff1a; 从功能的角度分为 1、串行&#xff1a;Serial、Serial Old 2、吞吐量优先&#xff1a;Parallel Scavenge、Parallel Old 3、响应时间优先&#xff1a;CMS 吞吐量优先VS响应时间优先 吞吐量运行用户代码时间/(运行用户代码…

如何通过ETL实现快速同步美团订单信息

一、美团外卖现状 美团作为中国领先的生活服务电子商务平台&#xff0c;其旗下的美团外卖每天承载着大量的订单信息。这些订单信息需要及时入库、清洗和同步&#xff0c;但由于数据量庞大且来源多样化&#xff0c;传统的手动处理方式效率低下&#xff0c;容易出错。比如&#…

ANTLR4规则解析生成器(一):入门

文章目录 1 什么是ANTLR42 为什么需要ANTLR43 环境搭建4 官方示例4.1 编写语法规则文件4.2 生成语法解析器4.3 基于SDK实现逻辑 5 总结 1 什么是ANTLR4 ANTLR是ANother Tool for Language Recognition的缩写&#xff0c;它是一个强大的用于读取、处理、执行和翻译结构化文本或…

数据库性能监控 ,数据库可用性监控 #mysql##oracle##SQLserver#_

当谈到监控数据库的性能和可用性时&#xff0c;涉及的方面多种多样。数据库是许多组织业务中的关键组成部分&#xff0c;因此确保其高性能和不间断可用性对于业务的成功至关重要。因此建立一个全面的监控系统至关重要。让我们深入探讨数据库性能和可用性监控的各个方面。 数据…