easy-poi導出and導入一對多數據excel

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.pswp.cn/pingmian/72088.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/72088.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/72088.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

c#如何直接獲取json中的某個值

在 C# 中直接獲取 JSON 中的某個值,通常可以通過以下方法實現(以 Newtonsoft.Json 和 .NET 內置的 System.Text.Json 為例): 方法 1:使用 System.Text.Json(.NET 內置庫) using System.Text.Json;// 示例 JSON 字符串 string json = @"{""name"&qu…

WPS二次開發系列:Android 第三方應用如何獲取WPS端內文檔

1.需求場景 在項目開發中碰到這種情況&#xff0c;我們需要利用WPS的文檔管理能力&#xff0c;比如需要調用WPS的文件選擇器&#xff0c;來選擇文檔&#xff0c;同時需要得到WPS選擇的文檔結果返回給我們的應用。之前在網上找到了很久都沒有找到WPS移動端有相關的API接口文檔和…

Pytesseract識別圖片

1. Pytesseract識別圖片原理 1.1 Tesseract引擎工作原理 Tesseract OCR 引擎是一個功能強大的開源文字識別工具&#xff0c;其工作原理可以分為以下幾個關鍵步驟&#xff1a; 圖像預處理&#xff1a;Tesseract 首先對輸入的圖像進行預處理&#xff0c;包括灰度化、二值化、去…

Flutter 基礎組件 Text 詳解

目錄 1. 引言 2. 基本使用 3. 自定義樣式 4. 文本對齊與溢出控制 5. 外邊距 5.1 使用 Container 包裹 5.2 使用 Padding 組件 5.3 在 Row/Column 中使用 5.4 動態邊距調整 5.5 關鍵區別說明 5.6 設置 margin 無效 6. 結論 相關推薦 1. 引言 Text 組件是 Flutter 中…

Acknowledgment.nack方法重試消費kafka消息異常

文章目錄 問題示例異常 原因nack方法Acknowledgment接口實現類&#xff1a;ConsumerAcknowledgment實現類&#xff1a;ConsumerBatchAcknowledgment 解決方案1 批量消費指定index示例 2 單條消費示例 問題 使用BatchAcknowledgingMessageListener 批量消費Kafka消息&#xff0…

Java 反序列化 - commons collection 之困(一)

#01多余的碎碎念 說到 java 反序列化&#xff0c;去搜索的話能看到網上有很多分析關于 commons collection 利用鏈的文章&#xff0c;emm 我一開始看不懂&#xff0c;看到很多代碼的圖頭暈。 這篇文章的話其實是我跟著 p 神的文章一路走下來的&#xff0c;所以整個邏輯會按照…

python LLM工具包

阿里云鏡像pypi http://mirrors.aliyun.com/pypi/simple/ modelscope魔塔 pip install modelscope https://modelscope.cn/docs/models/download Sentence-transformers pip install -U sentence-transformers pip3 install torch -i https://pypi.tuna.tsinghua.edu.cn/sim…

Linux賬號和權限管理

用戶賬戶管理 理論 /etc/passwd 該目錄用于保存用戶名&#xff0c;宿主目錄&#xff0c;登錄shel等基本信息 /etc/shadow 該目錄用于保存 用戶密碼&#xff0c;賬戶有效期等信息 圖上每一行中都有用“&#xff1a;”隔斷的字段 字段含義&#xff1a; 第1字段:用戶賬號的名…

晉升系列4:學習方法

每一個成功的人&#xff0c;都是從底層開始打怪&#xff0c;不斷的總結經驗&#xff0c;一步一步打上來的。在這個過程中需要堅持、總結方法論。 對一件事情長久堅持的人其實比較少&#xff0c;在堅持的人中&#xff0c;不斷的總結優化的更少&#xff0c;所以最終達到高級別的…

win32匯編環境,對話框中使用樹形視圖示例四

;運行效果,當點擊張遼時,展示張遼的圖像 ;當點擊曹仁時,展示曹仁的圖像 ;win32匯編環境,對話框中使用樹形視圖示例四 ;當點擊樹形視圖treeview控件中的某項時,展示某些功能。這里展示的是當點到某個將領時,顯示某個將領的圖像 ;直接抄進RadAsm可編譯運行。重要部分加備注。…

智慧停車小程序:實時車位查詢、導航與費用結算一體化

智慧停車小程序:實時車位查詢、導航與費用結算一體化 一、城市停車困境的數字化突圍 中國機動車保有量突破4.3億輛,但車位供給缺口達8000萬。傳統停車管理模式存在三大致命傷: 盲盒式尋位:62%的車主遭遇"地圖顯示有位,到場已滿員"的窘境迷宮式導航:商場停車場…

Windows server網絡安全

摘要 安全策略 IP安全策略&#xff0c;簡單的來說就是可以通過做相應的策略來達到放行、阻止相關的端口&#xff1b;放行、阻止相關的IP&#xff0c;如何做安全策略&#xff0c;小編為大家詳細的寫了相關的步驟&#xff1a; 解說步驟&#xff1a; 阻止所有&#xff1a; 打…

充電樁快速搭建springcloud(微服務)+前后端分離(vue),客戶端實現微信小程序+ios+app使用uniapp(一處編寫,處處編譯)

充電樁管理系統是專為中小型充電樁運營商、企業和個人開發者設計的一套高效、靈活的管理平臺。系統基于Spring Cloud微服務架構開發&#xff0c;采用模塊化設計&#xff0c;支持單機部署與集群部署&#xff0c;能夠根據業務需求動態擴展。系統前端使用uniapp框架&#xff0c;可…

小肥柴慢慢手寫數據結構(C篇)(4-3 關于棧和隊列的討論)

小肥柴慢慢學習數據結構筆記&#xff08;C篇&#xff09;&#xff08;4-3 關于棧和隊列的討論&#xff09; 目錄1 雙端棧/隊列2 棧與隊列的相互轉化2-1 棧轉化成隊列2-2 隊列轉化成棧 3 經典工程案例3-1 生產者和消費者模型&#xff08;再次重溫環形緩沖區&#xff09;3-2 MapR…

labview實現大小端交換移位

在解碼時遇到了大小端交換的問題&#xff0c;需要把高低字節的16進制值進行互換&#xff0c;這里一時間不知道怎么操作&#xff0c;本來打算先把16進制轉字節數組&#xff0c;算出字節數組的大小&#xff0c;然后通過模2得到0&#xff0c;1&#xff0c;來判斷是否為奇數位和偶數…

在Windows系統上安裝和配置Redis服務

&#x1f31f; 在Windows系統上安裝和配置Redis服務 Redis是一個高性能的鍵值存儲數據庫&#xff0c;廣泛用于緩存、消息隊列和實時分析等場景。雖然Redis最初是為Linux設計的&#xff0c;但也有Windows版本可供使用。今天&#xff0c;我將詳細介紹如何在Windows系統上安裝Red…

Ateme在云端構建可擴展視頻流播平臺

Akamai Connected Cloud幫助Ateme客戶向全球觀眾分發最高質量視頻內容。 “付費電視運營商和內容提供商現在可以在Akamai Connected Cloud上通過高質量視頻吸引觀眾&#xff0c;并輕松擴展。”── Ateme首席戰略官Rmi Beaudouin ? Ateme是全球領先的視頻壓縮和傳輸解決方案提…

DeepSeek進階應用(一):結合Mermaid繪圖(流程圖、時序圖、類圖、狀態圖、甘特圖、餅圖)

&#x1f31f;前言: 在軟件開發、項目管理和系統設計等領域&#xff0c;圖表是表達復雜信息的有效工具。隨著AI助手如DeepSeek的普及&#xff0c;我們現在可以更輕松地創建各種專業圖表。 名人說&#xff1a;博觀而約取&#xff0c;厚積而薄發。——蘇軾《稼說送張琥》 創作者&…

deepseek R1提供的3d迷宮設計方案

一、技術選型方案 核心渲染技術 &#x1f3a8; 采用Raycasting算法模擬3D透視效果使用Canvas 2D上下文進行逐像素繪制材質貼圖系統實現墻面差異化表現 迷宮數據結構 &#x1f5fa;? 二維數組存儲迷宮布局&#xff08;0:通路&#xff0c;1:墻體&#xff09;遞歸回溯算法生成隨…

時序數據庫TimescaleDB基本操作示例

好的&#xff01;以下是使用 TimescaleDB 的 Java 示例&#xff08;基于 JDBC&#xff0c;因為 TimescaleDB 是 PostgreSQL 的擴展&#xff0c;官方未提供獨立的 Java SDK&#xff09;&#xff1a; 1. 添加依賴&#xff08;Maven&#xff09; <dependency><groupId&g…