欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot使用Apache?POI實(shí)現(xiàn)導(dǎo)入導(dǎo)出Excel文件

 更新時間:2025年01月08日 10:09:42   作者:孤蓬&聽雨  
Apache?POI?是一個強(qiáng)大的?Java?庫,用于處理?Microsoft?Office?文檔,下面我們來看看SpringBoot如何使用Apache?POI導(dǎo)入導(dǎo)出Excel文件功能吧

1. Apache POI 簡介

Apache POI 是一個強(qiáng)大的 Java 庫,用于處理 Microsoft Office 文檔,包括 Excel 文件(.xls 和 .xlsx)。在 Java Spring Boot 項(xiàng)目中,利用 Apache POI 可以方便地實(shí)現(xiàn) Excel 文件的導(dǎo)入(讀?。┖蛯?dǎo)出(寫入)功能。

1.1 Apache POI 的特點(diǎn)

特性詳細(xì)說明
支持多種 Office 文檔格式包括 Excel(.xls 和 .xlsx)、Word、PowerPoint 等
功能全面支持 Excel 的各種復(fù)雜功能,如公式、圖表、樣式、單元格格式、數(shù)據(jù)驗(yàn)證、宏等
豐富的 API提供了 HSSF(用于 .xls)、XSSF(用于 .xlsx)和 SXSSF(用于大數(shù)據(jù)量的 .xlsx)等不同的實(shí)現(xiàn)類,支持對 Excel 文件的細(xì)粒度控制
社區(qū)活躍作為 Apache 基金會項(xiàng)目,擁有活躍的社區(qū)和豐富的文檔資源,便于開發(fā)者獲取幫助和解決問題
靈活性高提供了豐富的配置選項(xiàng)和 API,開發(fā)者可以根據(jù)需要進(jìn)行高度定制,滿足復(fù)雜的業(yè)務(wù)需求
支持讀寫操作不僅支持讀取 Excel 文件,還支持創(chuàng)建和修改 Excel 文件,包括添加、刪除、修改單元格內(nèi)容和格式

1.2 Apache POI 的優(yōu)點(diǎn)

優(yōu)點(diǎn)詳細(xì)說明
功能強(qiáng)大能夠處理 Excel 的各種高級功能,適用于需要全面操作 Excel 文件的場景
廣泛支持支持多種 Office 文檔格式,適用于不同的應(yīng)用場景,如數(shù)據(jù)導(dǎo)入導(dǎo)出、報表生成等
靈活性高提供了豐富的 API 和配置選項(xiàng),開發(fā)者可以根據(jù)具體需求進(jìn)行定制,實(shí)現(xiàn)復(fù)雜的業(yè)務(wù)邏輯
社區(qū)支持作為開源項(xiàng)目,擁有活躍的社區(qū)和豐富的文檔資源,便于開發(fā)者獲取幫助和解決問題
兼容性良好與多種 Java 版本和框架兼容,能夠很好地集成到現(xiàn)有的 Java 項(xiàng)目中

1.3 Apache POI 的缺點(diǎn)

缺點(diǎn)詳細(xì)說明
內(nèi)存消耗大處理大型 Excel 文件時,內(nèi)存消耗較大,容易導(dǎo)致內(nèi)存溢出(OutOfMemoryError)。特別是使用 HSSF 和 XSSF 時,這個問題尤為明顯
性能較低相比于一些輕量級的庫(如 EasyExcel),Apache POI 在處理大規(guī)模數(shù)據(jù)時的性能較低,處理時間較長
復(fù)雜性較高由于功能全面,API 較為復(fù)雜,學(xué)習(xí)曲線較陡,開發(fā)者需要花費(fèi)更多時間學(xué)習(xí)和掌握
文件體積較大生成的 Excel 文件體積可能較大,特別是在包含大量數(shù)據(jù)或復(fù)雜格式時,可能會影響文件傳輸和存儲效率
部分功能不夠完善盡管功能全面,但在某些高級功能(如某些復(fù)雜的圖表類型、宏支持等)上可能不如 Microsoft Office 本身的功能完善

2. 實(shí)現(xiàn) Excel 導(dǎo)入與導(dǎo)出

2.1 引用項(xiàng)目依賴

在 pom.xml 中添加 Apache POI 的依賴:

<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Apache POI 依賴 -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.2.3</version>
    </dependency>

    <!-- Lombok (可選,用于簡化代碼) -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>

    <!-- 其他依賴 -->
</dependencies>

2.2 定義數(shù)據(jù)模型

定義與 Excel 列對應(yīng)的 Java 類:

package com.example.exceldemo;

import lombok.Data;

@Data
public class UserData {

    private Integer id;

    private String name;

    private Integer age;

    private String email;
}

2.3 Excel 導(dǎo)入導(dǎo)出Controller類

創(chuàng)建 ExcelController 類,包含導(dǎo)出和導(dǎo)入接口:

package com.example.exceldemo;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@RestController
public class ExcelController {

    @GetMapping("/export")
    public ResponseEntity<byte[]> exportExcel() {
        String fileName = "用戶數(shù)據(jù).xlsx";
        List<UserData> userList = generateUserData();

        byte[] bytes = exportToExcel(userList);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", fileName);

        return ResponseEntity.ok()
                .headers(headers)
                .body(bytes);
    }

    private List<UserData> generateUserData() {
        List<UserData> list = new ArrayList<>();
        for (int i = 1; i <= 100; i++) {
            UserData user = new UserData();
            user.setId(i);
            user.setName("用戶" + i);
            user.setAge(20 + i % 30);
            user.setEmail("user" + i + "@example.com");
            list.add(user);
        }
        return list;
    }

    private byte[] exportToExcel(List<UserData> userList) {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("用戶數(shù)據(jù)");

        // 創(chuàng)建表頭
        Row header = sheet.createRow(0);
        header.createCell(0).setCellValue("編號");
        header.createCell(1).setCellValue("姓名");
        header.createCell(2).setCellValue("年齡");
        header.createCell(3).setCellValue("郵箱");

        // 寫入數(shù)據(jù)
        for (int i = 0; i < userList.size(); i++) {
            Row row = sheet.createRow(i + 1);
            UserData user = userList.get(i);
            row.createCell(0).setCellValue(user.getId());
            row.createCell(1).setCellValue(user.getName());
            row.createCell(2).setCellValue(user.getAge());
            row.createCell(3).setCellValue(user.getEmail());
        }

        // 寫入到字節(jié)數(shù)組
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return out.toByteArray();
    }

    @PostMapping("/import")
    public String importExcel(@RequestParam("file") MultipartFile file) {
        try (InputStream inputStream = file.getInputStream()) {
            List<UserData> userList = new ArrayList<>();
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> iterator = sheet.iterator();

            // 跳過表頭
            if (iterator.hasNext()) {
                iterator.next();
            }

            while (iterator.hasNext()) {
                Row row = iterator.next();
                UserData user = new UserData();
                user.setId((int) row.getCell(0).getNumericCellValue());
                user.setName(row.getCell(1).getStringCellValue());
                user.setAge((int) row.getCell(2).getNumericCellValue());
                user.setEmail(row.getCell(3).getStringCellValue());
                userList.add(user);
            }

            // 處理導(dǎo)入的數(shù)據(jù),例如保存到數(shù)據(jù)庫
            processUserData(userList);

            return "導(dǎo)入成功,共導(dǎo)入 " + userList.size() + " 條數(shù)據(jù)";
        } catch (IOException e) {
            e.printStackTrace();
            return "導(dǎo)入失敗: " + e.getMessage();
        }
    }

    private void processUserData(List<UserData> userList) {
        // 這里可以添加將數(shù)據(jù)保存到數(shù)據(jù)庫的邏輯
        // 例如使用 JPA 或 MyBatis 等持久層框架
        userList.forEach(user -> {
            // 模擬保存操作
            System.out.println("保存用戶: " + user);
        });
    }
}

2.4 前端部分(可選)

為了測試導(dǎo)入功能,可以創(chuàng)建一個簡單的 HTML 表單:

<!DOCTYPE html>
<html>
<head>
    <title>Excel 導(dǎo)入</title>
</head>
<body>
    <h1>導(dǎo)入 Excel 文件</h1>
    <form method="POST" enctype="multipart/form-data" action="/import">
        <input type="file" name="file" accept=".xlsx, .xls" />
        <button type="submit">上傳</button>
    </form>
</body>
</html>

將這個 HTML 文件放在 src/main/resources/static 目錄下,例如 src/main/resources/static/import.html,然后訪問 http://localhost:8080/import.html 即可看到上傳表單。

2.5 運(yùn)行項(xiàng)目

1.啟動 Spring Boot 應(yīng)用。

2.訪問 http://localhost:8080/import.html。

3.點(diǎn)擊“上傳”按鈕,選擇包含用戶數(shù)據(jù)的 Excel 文件進(jìn)行導(dǎo)入。

結(jié)果如下:

4.訪問 http://localhost:8080/export,將下載一個包含示例用戶數(shù)據(jù)的 Excel 文件。

3. 總結(jié)

Apache POI 是一個功能強(qiáng)大的 Java 庫,適用于在 Spring Boot 項(xiàng)目中處理 Excel 文件的導(dǎo)入與導(dǎo)出。通過使用 Apache POI,開發(fā)者可以方便地實(shí)現(xiàn)對 Excel 文件的讀寫操作,包括處理復(fù)雜的 Excel 功能。然而,Apache POI 在處理大型文件時內(nèi)存消耗較大,性能相對較低,因此在處理大規(guī)模數(shù)據(jù)時需要謹(jǐn)慎。

在本文中,我們詳細(xì)介紹了如何使用 Apache POI 在 Spring Boot 中實(shí)現(xiàn) Excel 文件的導(dǎo)入與導(dǎo)出,包括數(shù)據(jù)模型的定義、控制器接口的實(shí)現(xiàn)以及前后端交互的實(shí)現(xiàn)。通過本文的示例代碼,大家可以快速上手并在實(shí)際項(xiàng)目中應(yīng)用這些技術(shù)。

以上就是SpringBoot使用Apache POI實(shí)現(xiàn)導(dǎo)入導(dǎo)出Excel文件的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot Apache POI導(dǎo)入導(dǎo)出Excel的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論