【贫民版】Springboot导入返回错误Excel表格 ---- 通过session存储字节数据,再获取写到响应体中。

目录

  • 前言
  • 一、需求
  • 二、需求分析
  • 三、代码


前言

在开发中会遇到导入文件后,失败的数据需要整理在加上导入失败原因。

按照目前主流的方法,要么通过流输出到response响应体中,或者把失败的excel上传到服务器中,返回url让前端下载。


一、需求

导入文件后,把未满足条件的记录和未满足的原因导出,让业务人员修改后二次导入。

二、需求分析

1、当前端请求到后端时,可以直接通过response直接导出文件,但是会有其他情况,前端需要返回码去判断展示不同的页面。

2、故放弃第1种方法,需要让 excel 暂存在一个地方 , 通过返回的数据, 由前端判断去获取excel。

3、有多种实现方法。 本文主要介绍的是在 session中存储。

三、代码

相关依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.3.2</version>
</dependency>

controller

package com.example.springboot_demo.testImpl;import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;@RestController
@Slf4j
public class TestController {@GetMapping("/import")public String test2(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request){// TODO 处理file// 构造错误数据List<TempFileUtil.ErrorExportVO> errorExportVOList = new ArrayList<>();TempFileUtil.ErrorExportVO exportVO1 = new TempFileUtil.ErrorExportVO();exportVO1.setFileName("我是错误的文件名!");exportVO1.setErrorMsg("文件名错误!");TempFileUtil.ErrorExportVO exportVO2 = new TempFileUtil.ErrorExportVO();exportVO2.setFileName("我是错误的文件名2!");exportVO2.setErrorMsg("文件名错误2!");errorExportVOList.add(exportVO1);errorExportVOList.add(exportVO2);String uuid;try{ByteArrayOutputStream outputStream = new ByteArrayOutputStream();ExcelWriterBuilder write = EasyExcel.write(outputStream, TempFileUtil.ErrorExportVO.class);write.sheet("sheet1").doWrite(errorExportVOList);uuid = TempFileUtil.addExcel(request, outputStream, "错误信息");outputStream.close();}catch (Exception e) {throw new RuntimeException(e);}return uuid;}//下载临时文件@GetMapping("/downloadTempFile")public void downloadTempFile(@RequestParam("tempFileId") String tempFileId,HttpServletRequest request, HttpServletResponse response) {final TempFileUtil.TempFileBean fileBean = TempFileUtil.get(request, tempFileId);if (fileBean == null) {throw new RuntimeException("对象不存在!");}TempFileUtil.exportBinary(fileBean, response);TempFileUtil.remove(request, tempFileId);}
}

工具类。 为了方便阅读,把实体类放到里面了。

package com.example.springboot_demo.testImpl;import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;@Slf4j
public class TempFileUtil {@SuppressWarnings("unchecked")private static Map<String, TempFileBean> getFileMap(HttpServletRequest request) {if (request == null) {return new HashMap<>();}final HttpSession session = request.getSession();if (session.getAttribute("fileMap") == null) {session.setAttribute("fileMap", new HashMap<String, TempFileBean>());}return (Map<String, TempFileBean>) session.getAttribute("fileMap");}public static void put(HttpServletRequest request, final TempFileBean fileBean) {getFileMap(request).put(fileBean.getFileId(), fileBean);}public static TempFileBean get(HttpServletRequest request, final String fileId) {return getFileMap(request).get(fileId);}public static void remove(HttpServletRequest request, final String fileId) {getFileMap(request).remove(fileId);}public static String addExcel(HttpServletRequest request, ByteArrayOutputStream outputStream, String fileName) {byte[] excelData = outputStream.toByteArray();TempFileBean fileBean = new TempFileBean();String fileId = UUID.randomUUID().toString();fileBean.setFileId(fileId);fileBean.setFileName(fileName);fileBean.setFileContent(excelData);TempFileUtil.put(request, fileBean);return fileId;}public static void exportBinary(TempFileBean fileBean, HttpServletResponse response) {try {// 对中文文件名进行 URL 编码String encodedFileName = URLEncoder.encode(fileBean.getFileName(), "utf-8") + ExcelTypeEnum.XLSX.getValue();response.setContentType("multipart/form-data");response.setCharacterEncoding("utf-8");response.setContentType("application/vnd.ms-excel;charset=utf-8");response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);try (OutputStream os = response.getOutputStream()) {os.write(fileBean.getFileContent());os.flush();} catch (Exception e) {log.info("系统异常");}} catch (Exception e) {log.info("系统异常");}}@Datapublic static class TempFileBean {private String fileId;private String fileName;private byte[] fileContent;}@Datapublic static class ErrorExportVO {@ExcelProperty(value = "文件名")@ColumnWidth(30)private String fileName;@ExcelProperty(value = "错误原因")@ColumnWidth(30)private String errorMsg;}
}

在这里插入图片描述

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

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

相关文章

uniapp对接萤石云 实现监控播放、云台控制、截图、录像、历史映像等功能

萤石云开发平台地址&#xff1a;文档概述 萤石开放平台API文档 (ys7.com) 萤石云监控播放 首先引入萤石云js js地址&#xff1a;GitHub - Ezviz-OpenBiz/EZUIKit-JavaScript-npm: 轻应用npm版本&#xff0c;降低接入难度&#xff0c;适配自定义UI&#xff0c;适配主流框架 vi…

Linux(CentOS)/Windows-C++ 云备份项目(客户端文件操作类,数据管理模块设计,文件客户端类设计)

文章目录 1. 客户端文件操作类2. 客户端数据管理模块设计3. 文件客户端类设计项目代码 客户端负责的功能 指定目录的文件检测&#xff0c;获取文件夹里面的文件 判断这个文件是否需要备份&#xff0c;服务器备份过的文件则不需要进行备份&#xff0c;已经备份的文件如果修改也…

2024-03-28 Quest3 开发环境配置教程

文章目录 准备条件1 登录 Meta 账号2 Oculus 软件下载与配置3 下载 Quest3 开发包4 Unity 环境配置环境测试 准备条件 Quest3 头显一个。一根 USB 3.0 数据线。魔法。 ​ 有关 quest3 激活与配置可参考 B 站 UP &#xff1a;“南七月nqy_”。跳转链接&#xff1a;https://spa…

代码随想录day30(2)回溯:组合(leetcode77)

题目要求&#xff1a;给定两个整数 n 和 k&#xff0c;返回 1 ... n 中所有可能的 k 个数的组合。 思路&#xff1a;首先定义两个变量&#xff0c;一个存放符合条件的单一结果&#xff0c;另一个存放符合条件结果的集合&#xff0c;for循环用来横向遍历&#xff0c;递归用来纵…

Postman Tests设置Global读取不是最新值,跟Tests执行顺序有关(踩坑笔记)

前言 在执行Run Collection的时候&#xff0c;发现设置的全局变量每次读取都是旧值&#xff0c;没有读取到最新的值。 背景 有2个地方需要动态参数&#xff0c;一个URL&#xff0c;一个Body&#xff0c;因此需要设置Tests脚本。 url动态参数 url&#xff1a;动态参数projec…

目标检测的相关模型图:YOLO系列和RCNN系列

目标检测的相关模型图&#xff1a;YOLO系列和RCNN系列 前言YOLO系列的图展示YOLOpassthroughYOLO2YOLO3YOLO4YOLO5 RCNN系列的图展示有关目标检测发展的 前言 最近好像大家也都在写毕业论文&#xff0c;前段时间跟朋友聊天&#xff0c;突然想起自己之前写画了一些关于YOLO、Fa…

第5章.零、单例与小样本提示词的编写之道

零提示、单个提示和小样本提示是用于从ChatGPT中生成文本的技术。在数据匮乏或任务全新、定义模糊之时&#xff0c;我们用微妙的提示&#xff0c;让ChatGPT从无到有&#xff0c;生成文本。 面对任务&#xff0c;空无一例&#xff1a;模型凭借对任务的广泛理解&#xff0c;独辟…

鸿蒙OS开发实例:【手撸服务卡片】

介绍 服务卡片指导文档位于“开发/应用模型/Stage模型开发指导/Stage模型应用组件”路径下&#xff0c;说明其极其重要。 本篇文章将分享实现服务卡片的过程和代码 准备 请参照[官方指导]&#xff0c;创建一个Demo工程&#xff0c;选择Stage模型 鸿蒙OS开发更多内容↓点击…

1学习使用axios

一、axios介绍&#xff1a; axios 是一个基于 Promise 的 HTTP 客户端&#xff0c;用于浏览器和 Node.js。它提供了一种简单的方法来发送 HTTP 请求&#xff0c;并且具有很多实用的功能&#xff0c;使得网络请求变得更加方便和可靠。 以下是 axios 的一些主要特点和功能&…

Machine Learning机器学习之统计分析

目录 前言 机器学习之统计分析 统计学的主要目标包括&#xff1a; 统计学核心概念&#xff1a; 统计基础&#xff1a; 训练误差&#xff1a; 常见的损失函数&#xff1a; 正则化和交叉验证 博主介绍&#xff1a;✌专注于前后端、机器学习、人工智能应用领域开发的优质创作者、秉…

如何制作蛋糕店小程序_开启您的蛋糕店小程序之旅

甜蜜滋味&#xff0c;一触即达——开启您的蛋糕店小程序之旅 在这个快节奏的时代&#xff0c;人们对美食的追求从未停歇。尤其是那些色香味俱佳、口感细腻的蛋糕&#xff0c;更是成为了许多人生活中的小确幸。然而&#xff0c;忙碌的工作和生活常常让我们无法亲自前往蛋糕店&a…

关于web_server项目的学习记录(自用)

主要参考资料&#xff1a; 我在地铁吃闸机 基础处理框架&#xff1a;Multi-reactor muduo库有三个核心组件实现持续监听reactor的fd&#xff1a;channel;epoll/poller/eventloop类 channel 事件监听器epoll_ctl监听到了fd发生了什么事件,channel类会封装每个fd和fd感兴趣的事…