easy-poi导出and导入一对多数据excel

devtools/2025/3/13 22:34:28/

easy-poi导出and导入一对多数据excel

一、导入jar包

        <!-- easy-poi --><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-spring-boot-starter</artifactId><version>4.4.0</version></dependency>

二、创建excel对象

father-obj

package com.example.excel.easypoi.entity.my;import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelCollection;
import lombok.Data;import java.io.Serializable;
import java.util.Date;
import java.util.List;@Data
public class Father implements Serializable {@Excel(name = "编号", needMerge = true)private String id;@Excel(name = "姓名", needMerge = true)private String name;@Excel(name = "头像",type = 2,imageType = 2,width = 20,height = 15, needMerge = true)private byte[] logo;@Excel(name="年龄", orderNum="3", suffix="岁",needMerge = true)private Integer age;@Excel(name="生日", width=20.0, format="yyyy-MM-dd HH:mm:ss", orderNum="2",needMerge = true)private Date bir;@Excel(name = "状态", width = 25, replace = {"待审_0", "通过_1"}, addressList = true, needMerge = true)private String status;@ExcelCollection(name = "子列表")private List<Son> sonList;
}

son-obj

package com.example.excel.easypoi.entity.my;import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;import java.io.Serializable;
@Data
public class Son  implements Serializable {@Excel(name="子编号")private String id;@Excel(name="子姓名")private String name;}

三、工具类

package com.example.excel.easypoi.util;import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** @author: reshui* description:* DateTime:2025/2/20-11:17*/
@Slf4j
public class EasyPoiExcelUtil {/*** 通用的 Excel 导入方法* @param file 上传的 Excel 文件* @param clazz 要导入的数据类型的 Class 对象* @param titleRows 标题所占的行数* @param headRows 表头所占的行数* @param <T> 泛型类型,表示要导入的数据类型* @return 包含导入数据的列表* @throws Exception 当读取文件输入流出现异常时抛出*/public static <T> List<T> importExcel(MultipartFile file, Class<T> clazz, int titleRows, int headRows) throws Exception {// 导入配置参数ImportParams params = new ImportParams();// 标题占几行params.setTitleRows(titleRows);// 表头占几行params.setHeadRows(headRows);// 参数1:输入流  参数2:导入的数据类型  参数3:导入配置参数return ExcelImportUtil.importExcel(file.getInputStream(), clazz, params);}public static void download(HttpServletResponse response, ExportParams exportParams,Class<?> clazz, List<?> data,String fileName) throws IOException {try {Workbook workbook = ExcelExportUtil.exportExcel(exportParams, clazz, data);response.setCharacterEncoding("UTF-8");response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");workbook.write(response.getOutputStream());workbook.close();} catch (Exception e) {log.error("导出Excel异常:", e);response.reset();response.setContentType("application/json");response.setCharacterEncoding("utf-8");Map<String, String> map = new HashMap<String, String>();map.put("status", "failure");map.put("message", "下载文件失败" + e.getMessage());response.getWriter().println(JSON.toJSONString(map));}}}

四、controller-api接口层

package com.example.excel.easypoi.controller;import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.example.excel.easypoi.entity.my.Father;
import com.example.excel.easypoi.entity.my.Son;
import com.example.excel.easypoi.util.EasyPoiExcelUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;/*** @author: ly* description:* DateTime:2025/2/20-10:25*/
@RestController
@RequestMapping("/easyCommon")
public class EasyPoiCommonController {@PostMapping("import")public List<Father> importData(MultipartFile file) throws Exception {List<Father> dataList = EasyPoiExcelUtil.importExcel(file, Father.class, 0, 2);dataList.forEach(System.out::println);return dataList;}@GetMapping("export")public void exportData(HttpServletResponse response, Integer x) throws Exception {List<Father> fatherList = getFatherList(x);EasyPoiExcelUtil.download(response, new ExportParams(), Father.class, fatherList, "用户信息列表");}public List<Father> getFatherList(Integer x) {List<Father> userList = new ArrayList<>();for (int i = 1; i <= x; i++) {Father user = new Father();user.setId("编号" + i);user.setName("姓名-" + i);user.setStatus(i % 2 == 0 ? "1" : "0");user.setBir(new Date());user.setAge(i);user.setLogo(null);Random rand = new Random();int num = rand.nextInt(5) + 1;List<Son> orderList = new ArrayList<>(num);for (int j = 1; j <= num; j++) {Son order = new Son();order.setId("订单号" + j);order.setName("商品" + j);orderList.add(order);}user.setSonList(orderList);userList.add(user);}return userList;}
}


http://www.ppmy.cn/devtools/166870.html

相关文章

YashanDB认证,YCA证书认证教程,免费证书,内含真题考试题库及答案——五分钟速成

目录 一.账号及平台注册登录流程 二.登录进行设备调试核验 三.考试&#xff08;考完获取分数&#xff09; 四.获取证书 五.题库及答案 一.账号及平台注册登录流程 1-点击这里进行账号注册&#xff08;首次学习必须先注册&#xff0c;有账号之后可以直接在2号链接登录&#…

手机遥控开关,是一种能让用户通过手机远程控制电器开关

移动管家手机遥控开关&#xff0c;是一种能让用户通过手机远程控制电器开关的智能设备。以YD238 - 6型为例&#xff0c;它可通过手机或座机远程控制&#xff0c;最大输出功率1100W&#xff0c;还可扩展大功率外挂接触器&#xff0c;具备来电、停电通知及记忆功能等&#xff0c;…

ESP8266远端可变的UDP传输

基本配置 1.配置WiFi模式 ATCWMODE3 响应&#xff1a;ok 2连接路由器 ATCWJAP“SSID”&#xff0c;“password” 响应&#xff1a;ok 3.查询ESP8266设备的IP地址 ATCIFSR 响应: CIFSR: APIP, "192.168.4.1" CIFSR: APMAC, "1a: fe: 34: a5:8d: c6&quo…

AtCoder ABC E - Min of Restricted Sum 题解

根据输入考虑建图&#xff0c;x、y两个下标的边权为z,建无向图 这样我们可以得到一些连通块。根据异或和的性质&#xff0c;对于每一个连通块&#xff0c;我们只要知道其中一个点的点权就能推出所有的点权。 最小值考虑贪心&#xff0c;针对当前连通图所有点权二进制数的每一…

SpringMVC 基本概念与代码示例

1. SpringMVC 简介 SpringMVC 是 Spring 框架中的一个 Web 层框架&#xff0c;基于 MVC&#xff08;Model-View-Controller&#xff09; 设计模式&#xff0c;提供了清晰的分层结构&#xff0c;适用于 Web 应用开发 SpringMVC 主要组件 DispatcherServlet&#xff08;前端控…

不同AI生成的PHP版雪花算法

OpenAI <?php /*** Snowflake 雪花算法生成器* 生成的 64 位 ID 结构&#xff1a;* 1 位 保留位&#xff08;始终为0&#xff0c;防止负数&#xff09;* 41 位 时间戳&#xff08;毫秒级&#xff0c;当前时间减去自定义纪元&#xff09;* 5 位 数据中心ID* 5 …

每天一篇《目标检测》文献(一)

今天看的是《改进 YOLOv8 的轻量化密集行人检测方法》。 目录 一、摘要 二、背景介绍 三、YOLOv8介绍 四 改进结构介绍 4.1 双卷积内核&#xff08;DualConv&#xff09; 4.2 RS-C2f模块 4.3 空间金字塔池化改进&#xff08;SPPELAN_BiFPN&#xff09; 4.4 损失函数优化…

SIP 协议详解:原理、用途与应用场景

1. SIP 协议简介 SIP&#xff08;Session Initiation Protocol&#xff0c;会话初始化协议&#xff09;是一个应用层协议&#xff0c;属于计算机网络的七层模型&#xff08;OSI 模型&#xff09;中的第七层。在计算机网络中&#xff0c;OSI 参考模型将网络通信划分为以下 7 层…