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

server/2025/3/14 8:35:52/

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/server/174833.html

相关文章

LINUX 指令大全

Linux服务器上有许多常用的命令&#xff0c;可以帮助你管理文件、目录、进程、网络和系统配置等。以下是一些常用的Linux命令&#xff1a; 文件和目录管理 ls&#xff1a;列出当前目录中的文件和子目录 bash lspwd&#xff1a;显示当前工作目录的路径 bash pwdcd&#xff1a;切…

【 Fail2ban 使用教程】

Fail2ban 使用教程 1. 安装 Fail2ban2. 配置 Fail2ban2.1 创建 jail.local 文件2.2 基本配置参数说明2.3 配置具体服务的监控规则2.3.1 SSH 服务2.3.2 Apache 服务 3. 启动和管理 Fail2ban3.1 启动 Fail2ban 服务3.2 设置 Fail2ban 开机自启3.3 检查 Fail2ban 服务状态3.4 重新…

[密码学实战]Java实现国密TLSv1.3单向认证

一、代码运行结果 1.1 运行环境 1.2 运行结果 1.3 项目架构 二、TLS 协议基础与国密背景 2.1 TLS 协议的核心作用 TLS(Transport Layer Security) 是保障网络通信安全的加密协议,位于 TCP/IP 协议栈的应用层和传输层之间,提供: • 数据机密性:通过对称加密算法(如 AE…

C++蓝桥杯基础篇(十一)

片头 嗨~小伙伴们&#xff0c;大家好&#xff01;今天我们来学习C蓝桥杯基础篇&#xff08;十一&#xff09;&#xff0c;学习类&#xff0c;结构体&#xff0c;指针相关知识&#xff0c;准备好了吗&#xff1f;咱们开始咯~ 一、类与结构体 类的定义&#xff1a;在C中&#x…

STM32 HAL库实战:高效整合DMA与ADC开发指南

STM32 HAL库实战&#xff1a;高效整合DMA与ADC开发指南 一、DMA与ADC基础介绍 1. DMA&#xff1a;解放CPU的“数据搬运工” DMA&#xff08;Direct Memory Access&#xff09; 是STM32中用于在外设与内存之间直接传输数据的硬件模块。其核心优势在于无需CPU干预&#xff0c;…

SpringBoot3+Lombok如何配置logback输出日志到文件

Background/Requirement SpringBoot3Lombok如何配置logback输出日志到文件&#xff0c;因为我需要对这些日志进行输出&#xff0c;控制台输出和文件输出&#xff0c;文件输出是为了更好的作为AuditLog且支持滚动式备份&#xff0c;每天一个文件。 Technical Solution 1.确保你…

计算机网络--访问一个网页的全过程

文章目录 访问一个网页的全过程应用层在浏览器输入URL网址http://www.aspxfans.com:8080/news/index.aspboardID5&ID24618&page1#r_70732423通过DNS获取IP地址生成HTTP请求报文应用层最后 传输层传输层处理应用层报文建立TCP连接传输层最后 网络层网络层对TCP报文进行处…

STM32F407 cubeIDE Bootloader APP 如何写

一、bootloader 代码如下&#xff1a; #define FLASH_JUMP_ADDR (0x0800c000) /* USER CODE END PD *//* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM *//* USER CODE END PM *//* Private variables ----------…