国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Spring Boot中Excel數(shù)據(jù)導入導出的高效實現(xiàn)

這篇具有很好參考價值的文章主要介紹了Spring Boot中Excel數(shù)據(jù)導入導出的高效實現(xiàn)。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

?? 前言

歡迎來到我的技術小宇宙!?? 這里不僅是我記錄技術點滴的后花園,也是我分享學習心得和項目經(jīng)驗的樂園。?? 無論你是技術小白還是資深大牛,這里總有一些內(nèi)容能觸動你的好奇心。??

  • ?? 洛可可白:個人主頁

  • ?? 個人專欄:?前端技術 ?后端技術

  • ?? 個人博客:洛可可白博客

  • ?? 代碼獲取:bestwishes0203

  • ?? 封面壁紙:洛可可白wallpaper

Spring Boot中Excel數(shù)據(jù)導入導出的高效實現(xiàn),spring boot,excel,后端

標題:Spring Boot中Excel數(shù)據(jù)導入導出的高效實現(xiàn)

摘要

在企業(yè)級應用中,Excel文件的導入導出是一個常見的需求。本文將介紹如何在Spring Boot項目中使用EasyExcel庫實現(xiàn)Excel文件的導入導出功能。我們將通過實際的代碼示例,展示如何讀取和寫入Excel文件,以及如何通過自定義監(jiān)聽器來增強數(shù)據(jù)處理的靈活性。

1. 依賴添加

首先,我們需要在項目的pom.xml文件中添加EasyExcel的依賴。

<!-- 導出excel -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.2.1</version>
</dependency>

2. 自定義監(jiān)聽器(可選)

為了增強數(shù)據(jù)處理的靈活性,我們可以創(chuàng)建一個自定義監(jiān)聽器來校驗Excel文件中的數(shù)據(jù)。例如,我們可以校驗用戶名稱是否重復,或者數(shù)據(jù)格式是否正確。

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.xiaohe.uploadimage.entity.User;

/**
 * 自定義監(jiān)聽器,對下載的excel中的數(shù)據(jù)進行校驗
 */

public class UserListener extends AnalysisEventListener {

    List<String> names = new ArrayList<>();

    /**
     * 每解析一行,回調(diào)該方法
     *
     * @param data
     * @param context
     */
    @Override
    public void invoke(Object data, AnalysisContext context) {
        //校驗名稱
        String name = ((User) data).getU_name();
//        if (StrUtil.isBlank(name)) {
//            throw new RuntimeException(String.format("第%s行名稱為空,請核實", context.readRowHolder().getRowIndex() + 1));
//        }
        if (names.contains(name)) {
            throw new RuntimeException(String.format("第%s行名稱已重復,請核實", context.readRowHolder().getRowIndex() + 1));
        } else {
            names.add(name);
        }
    }

    /**
     * 出現(xiàn)異?;卣{(diào)
     *
     * @param exception
     * @param context
     * @throws Exception
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        if (exception instanceof ExcelDataConvertException) {
            /**從0開始計算*/
            int columnIndex = ((ExcelDataConvertException) exception).getColumnIndex() + 1;
            int rowIndex = ((ExcelDataConvertException) exception).getRowIndex() + 1;
            String message = "第" + rowIndex + "行,第" + columnIndex + "列" + "數(shù)據(jù)格式有誤,請核實";
            throw new RuntimeException(message);
        } else if (exception instanceof RuntimeException) {
            throw exception;
        } else {
            super.onException(exception, context);
        }
    }

    /**
     * 解析完,全部回調(diào)
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        //解析完,全部回調(diào)邏輯實現(xiàn)
        names.clear();
    }
}

3. 實體類定義

我們需要定義一個實體類來映射Excel文件中的列。使用@ExcelProperty注解來指定Excel列的名稱。

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

// ... 其他代碼 ...

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {
    // ... 實體類屬性和注解 ...
     @ExcelProperty("賬號")
    private String u_acc;
    @ExcelProperty("密碼")
    private String u_pwd;
    @ExcelProperty("姓名")
    private String u_name;
    @ExcelProperty("性別")
    private String u_sex;
    @ColumnWidth(20)
    @DateTimeFormat("yyyy-MM-dd")
    @JsonFormat(pattern = "yyyy-MM-dd")
    @ExcelProperty("生日")
    private Date u_birth;
    @ExcelProperty("角色")
    private String u_ide;
    @ExcelProperty("狀態(tài)")
    private int u_statues;
    @ColumnWidth(20)
    @DateTimeFormat("yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @ExcelProperty("創(chuàng)建日期")
    private Date u_create_time;
}

4. 控制層實現(xiàn)

導出數(shù)據(jù)

在控制器中,我們提供一個接口來導出Excel文件。EasyExcel提供了便捷的API來生成Excel文件。

import com.alibaba.excel.EasyExcel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

// ... 其他代碼 ...

@RestController
public class ExcelController {
    
        @Autowired
    private ExcelMapper excelMapper;

    @GetMapping("user")
    public List<User> user() {
        return excelMapper.selectUserAll();
    }
    
     /**
     * 導出數(shù)據(jù)
     */
    @GetMapping("exportExcel")
    public void exportData(HttpServletResponse response) throws IOException {
        // ... 導出數(shù)據(jù)代碼 ...
         response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("用戶表", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        List<User> users = excelMapper.selectUserAll();
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), User.class).sheet("用戶表").doWrite(users);
    }
}

導入數(shù)據(jù)

同樣地,我們提供一個接口來處理Excel文件的導入。通過EasyExcel的讀取功能,我們可以將Excel文件中的數(shù)據(jù)轉(zhuǎn)換為Java對象。

import com.alibaba.excel.EasyExcel;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

// ... 其他代碼 ...

@RestController
public class ExcelController {
    /**
     * 導入數(shù)據(jù)
     */
    @PostMapping("/importExcel")
    public Integer importData(MultipartFile file) {
        try {
            //獲取文件的輸入流
            InputStream inputStream = file.getInputStream();
            List<User> lst = EasyExcel.read(inputStream) //調(diào)用read方法
                    //注冊自定義監(jiān)聽器,字段校驗可以在監(jiān)聽器內(nèi)實現(xiàn)
                    .registerReadListener(new UserListener())
                    .head(User.class) //對應導入的實體類
                    .sheet(0) //導入數(shù)據(jù)的sheet頁編號,0代表第一個sheet頁,如果不填,則會導入所有sheet頁的數(shù)據(jù)
                    .headRowNumber(1) //列表頭行數(shù),1代表列表頭有1行,第二行開始為數(shù)據(jù)行
                    .doReadSync(); //開始讀Excel,返回一個List<T>集合,繼續(xù)后續(xù)入庫操作
            //模擬導入數(shù)據(jù)庫操作
            for (User user : lst) {
                Date date = user.getU_birth();
                String form = String.format("%tF", date);
                System.out.println(form);
            }
            return 1;
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }
}

?? 結語

通過本文的介紹,我們學習了如何在Spring Boot項目中使用EasyExcel庫來實現(xiàn)Excel文件的導入導出。自定義監(jiān)聽器的引入使得數(shù)據(jù)處理更加靈活,能夠應對各種復雜的業(yè)務需求。EasyExcel的簡單易用和強大的功能,使得Excel文件處理變得高效和便捷。在實際開發(fā)中,開發(fā)者可以根據(jù)項目需求,選擇合適的庫來實現(xiàn)Excel文件的處理。

如果對你有幫助,點贊、收藏、關注是我更新的動力!??????文章來源地址http://www.zghlxwxcb.cn/news/detail-840137.html

?? 往期精彩回顧

  1. Spring Boot工程集成驗證碼生成與驗證功能教程
  • 文章瀏覽閱讀1.3k次,點贊17次,收藏38次。
  1. Spring Boot 3項目集成Swagger3教程
  • 文章瀏覽閱讀768次,點贊8次,收藏15次。
  1. Spring Boot中實現(xiàn)圖片上傳功能的兩種策略
  • 文章瀏覽閱讀1.1k次,點贊11次,收藏22次。
  1. VS code搭建C/C++運行環(huán)境簡單易上手
  • 文章瀏覽閱讀2.7k次,點贊8次,收藏5次。
  1. 入門指南:使用uni-app構建跨平臺應用
  • 文章瀏覽閱讀1.2k次,點贊29次,收藏9次。

到了這里,關于Spring Boot中Excel數(shù)據(jù)導入導出的高效實現(xiàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • 使用Spring Boot和EasyExcel的導入導出

    在當今信息化社會,數(shù)據(jù)的導入和導出在各種業(yè)務場景中變得越來越重要。為了滿足復雜的導入導出需求,結合Java編程語言、Spring Boot框架以及EasyExcel庫,我們可以輕松地構建出強大而靈活的數(shù)據(jù)處理系統(tǒng)。本文將引導您通過一個案例學習如何使用這些工具,實現(xiàn)一個復雜的

    2024年02月14日
    瀏覽(37)
  • spring boot 整合EasyPoi導入導出,下載模版功能

    spring boot 整合EasyPoi導入導出,下載模版功能

    name:Excel中的列名; width:指定列的寬度; needMerge:是否需要縱向合并單元格; format:當屬性為時間類型時,設置時間的導出導出格式; desensitizationRule:數(shù)據(jù)脫敏處理,3_4表示只顯示字符串的前3位和后4位,其他為*號; replace:對屬性進行替換; suffix:對數(shù)據(jù)添加后綴。

    2024年02月11日
    瀏覽(18)
  • Spring boot easyexcel 實現(xiàn)復合數(shù)據(jù)導出、按模塊導出

    Spring boot easyexcel 實現(xiàn)復合數(shù)據(jù)導出、按模塊導出

    場景: 導出數(shù)據(jù)為1對多的復合數(shù)據(jù) 一個模塊是一條數(shù)據(jù),直接填充數(shù)據(jù)無法實現(xiàn) 如圖: 紅框內(nèi)為一條數(shù)據(jù)(1對多),下方箭頭指向為第二條數(shù)據(jù) 如果直接填充,只能填充第一條,第二條就沒辦法了。 由于多行都包含許多,固定表頭,只能走填充路線,怎么實現(xiàn)呢 實現(xiàn)思路

    2024年02月07日
    瀏覽(19)
  • Spring Boot進階(19):探索ElasticSearch:如何利用Spring Boot輕松實現(xiàn)高效數(shù)據(jù)搜索與分析

    Spring Boot進階(19):探索ElasticSearch:如何利用Spring Boot輕松實現(xiàn)高效數(shù)據(jù)搜索與分析

    ????????ElasticSearch是一款基于Lucene的開源搜索引擎,具有高效、可擴展、分布式的特點,可用于全文搜索、日志分析、數(shù)據(jù)挖掘等場景。Spring Boot作為目前最流行的微服務框架之一,也提供了對ElasticSearch的支持。本篇文章將介紹如何在Spring Boot項目中整合ElasticSearch,并展

    2024年02月11日
    瀏覽(23)
  • Spring Boot進階(70):如何在Spring Boot中使用FastJson實現(xiàn)高效的JSON數(shù)據(jù)處理?

    Spring Boot進階(70):如何在Spring Boot中使用FastJson實現(xiàn)高效的JSON數(shù)據(jù)處理?

    ??隨著互聯(lián)網(wǎng)的發(fā)展,JSON(JavaScript Object Notation)已成為近年來使用最廣泛的數(shù)據(jù)交換格式之一。為了提高JSON數(shù)據(jù)的處理效率,目前市面上常用的JSON解析庫有Jackson、Gson、FastJson等。本文將介紹如何在Spring Boot中使用FastJson實現(xiàn)高效的JSON數(shù)據(jù)處理。 ??那么,具體如何實現(xiàn)

    2024年02月09日
    瀏覽(56)
  • Spring Boot 我隨手封裝了一個萬能的 Excel 導出工具,傳什么都能導出!

    Spring Boot 我隨手封裝了一個萬能的 Excel 導出工具,傳什么都能導出!

    如題,這個小玩意,就是不限制你查的是哪張表,用的是什么類。 我直接一把梭,嘎嘎給你一頓導出。 我知道,這是很多人都想過的, 至少我就收到很多人問過我這個類似的問題。 我也跟他們說了,但是他們就是不動手,其實真的很簡單。 不動手怎么辦? 我出手唄。 不多

    2024年02月06日
    瀏覽(23)
  • 使用easypoi-spring-boot-starter 4.1.1導入excel報錯NoSuchMethodError和NoSuchMethodError

    使用easypoi進行excel的導入遇到的錯誤以及解決辦法 easypoi項目地址:https://gitee.com/lemur/easypoi easypoi的Maven依賴: 報錯描述: 解決辦法: XmlOptions.setEntityExpansionLimit() 錯誤,是 jar 包版本引起的,3.0 版本以下的 xmlbeans 中根本沒有該方法,需要將jar升級到 3.0+ 版本才可以。另外

    2024年02月08日
    瀏覽(24)
  • Spring Boot進階(74):輕松實現(xiàn)高效SOAP服務! Spring Boot與CXF完美結合

    Spring Boot進階(74):輕松實現(xiàn)高效SOAP服務! Spring Boot與CXF完美結合

    ????????SOAP(簡單對象訪問協(xié)議)是一種基于XML的通信協(xié)議,它常用于Web服務的實現(xiàn)。在Java中,Apache CXF是一個流行的實現(xiàn)SOAP的框架,它實現(xiàn)了JAX-WS和JAX-RS標準。Spring Boot是一個快速開發(fā)Web應用的框架,它提供了許多自動化的配置和依賴注入的功能。在本文中,我們將要探

    2024年02月06日
    瀏覽(27)
  • Spring Boot進階(72):【教程】用Spring Boot和HttpClient實現(xiàn)高效的HTTP請求

    Spring Boot進階(72):【教程】用Spring Boot和HttpClient實現(xiàn)高效的HTTP請求

    ??隨著系統(tǒng)規(guī)模的不斷擴大和復雜度的提升,異步通信這種模式越來越被廣泛應用于各種分布式系統(tǒng)中。RocketMQ作為一個高性能、高可靠性、分布式消息隊列,得到了眾多企業(yè)的青睞。本文將介紹如何使用Spring Boot整合RocketMQ,實現(xiàn)異步通信。 ??那么,具體如何實現(xiàn)呢?這

    2024年02月09日
    瀏覽(32)
  • Spring Boot整合Redis的高效數(shù)據(jù)緩存實踐

    Spring Boot整合Redis的高效數(shù)據(jù)緩存實踐

    引言 在現(xiàn)代Web應用開發(fā)中,數(shù)據(jù)緩存是提高系統(tǒng)性能和響應速度的關鍵。Redis作為一種高性能的緩存和數(shù)據(jù)存儲解決方案,被廣泛應用于各種場景。本文將研究如何使用Spring Boot整合Redis,通過這個強大的緩存工具提高應用的性能和可伸縮性。 整合redis,需要先安裝redis Redis?

    2024年01月22日
    瀏覽(93)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包