最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot整合easyExcel實(shí)現(xiàn)CSV格式文件的導(dǎo)入導(dǎo)出

 更新時(shí)間:2024年02月25日 14:15:07   作者:夏林夕  
這篇文章主要為大家詳細(xì)介紹了SpringBoot整合easyExcel實(shí)現(xiàn)CSV格式文件的導(dǎo)入導(dǎo)出,文中的示例代碼講解詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴可以參考下

一:pom依賴

 <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.2</version>
        </dependency>
        <!-- java.lang.NoClassDefFoundError: org/apache/commons/compress/utils/Lists -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>1.21</version>
        </dependency>
 
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>ooxml-schemas</artifactId>
            <version>1.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.1.1</version>
        </dependency>
 
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.26</version>
            <scope>test</scope>
        </dependency>
 
 
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-csv</artifactId>
            <version>1.9.0</version>
        </dependency>
 
        <dependency>
            <groupId>com.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>5.6</version> <!-- 使用最新版本 -->
        </dependency>
 
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.73</version>
        </dependency>

二:檢查CSV內(nèi)容格式的工具類

checkCscUtils.java

package com.example.juc.test.Controller;
 
/**
 * @Author 
 * @Date Created in  2023/12/5 17:32
 * @DESCRIPTION:  判斷csv 文件內(nèi)容是否正確
 * @Version V1.0
 */
 
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
 
public class checkCscUtils {
    public static boolean isCsvFormatValid(MultipartFile file) {
        try (InputStream inputStream = file.getInputStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
             CSVParser parser = new CSVParser(reader, CSVFormat.DEFAULT.
                     withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim())) {
            // 獲取標(biāo)題
            List<String> headers = parser.getHeaderNames();
            int numberOfColumns = headers.size();
 
            for (CSVRecord record : parser) {
                // 檢查列數(shù)是否一致
                if (record.size() != numberOfColumns) {
                    return false;
                }
                // 這里可以添加更多的檢查,例如檢查數(shù)據(jù)類型等
            }
        } catch (IOException e) {
            e.printStackTrace();
            // 如果發(fā)生異常,認(rèn)為格式不正確
            return false;
        }
        // 所有檢查都通過,則認(rèn)為格式正確
        return true;
    }
}

三:Web端進(jìn)行測試

 
 
/**
 * @Author 
 * @Date Created in  2023/11/2 10:59
 * @DESCRIPTION: 讀取csv格式的文件數(shù)據(jù)
 * @Version V1.0
 */
 
@RestController
@RequestMapping("/api/csv")
public class CsvController {
 
    /**
     * 讀取傳入的csv  文本的內(nèi)容可以存入數(shù)據(jù)庫
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public ResponseEntity<?> uploadCsv(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("文件不能為空");
        }
        //判斷csv文件類型是不是csv文件
        String contentType = file.getContentType();
        String originalFilename = file.getOriginalFilename();
        boolean isCsv = ("text/csv".equals(contentType))
                || (originalFilename != null && originalFilename.endsWith(".csv"));
        if (!isCsv) {
            return ResponseEntity.badRequest().body("文件必須是CSV格式");
        }
        //判斷csv文件格式內(nèi)容是否有誤?
        boolean csvFormatValid = checkCscUtils.isCsvFormatValid(file);
        if (csvFormatValid) {
            List<User> userList = new CopyOnWriteArrayList<>();
            try {
                EasyExcel.read(file.getInputStream(), User.class,
                                new PageReadListener<User>(userList::addAll))
                        .excelType(ExcelTypeEnum.CSV)
                        .sheet()
                        .doRead();
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseEntity.status(500).body("文件讀取出錯(cuò)");
            }
 
            // 處理userList...
 
            return ResponseEntity.ok(userList);
        }
        return ResponseEntity.status(500).body("文件格式出錯(cuò)");
    }
 
    /**
     * 使用 easyExcel  導(dǎo)出一個(gè)csv 格式,但是版本可能與poi 版本沖突
     *
     * @param response
     * @return
     * @throws IOException
     */
    @GetMapping("/exportCsv")
    public ResponseEntity<?> exportCsv(HttpServletResponse response) throws IOException {
        // 設(shè)置響應(yīng)頭
        response.setContentType("application/csv");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("export_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))
                + ".csv");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
 
        List<Student> userList = getStudents();
 
        // 使用EasyExcel導(dǎo)出CSV文件response.getOutputStream()
        try {
            EasyExcel.write(response.getOutputStream(), Student.class)
                    .excelType(ExcelTypeEnum.CSV)
                    .sheet("我的學(xué)生")
                    .doWrite(userList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResponseEntity.status(200).body("文件導(dǎo)出成功");
    }
 
 
 
 
 
 
    private static List<Student> getStudents() {
        // 創(chuàng)建數(shù)據(jù)列表
        List<Student> userList = new CopyOnWriteArrayList<>();
        // 添加數(shù)據(jù)(示例)
        userList.add(new Student("1", "John Doe", "25"));
        userList.add(new Student("2", "Jane Smith", "30"));
        userList.add(new Student("3", "Mike Johnson", "35"));
        return userList;
    }
}

四:拓展使用

使用hutool工具類來進(jìn)行導(dǎo)出功能

    /**
     * 使用 hutool 工具類生成一個(gè)csv格式的文檔
     *
     * @param response
     * @return
     * @throws IOException
     */
    @GetMapping("/exportCsvHutool")
    public ResponseEntity<?> exportCsvHutool(HttpServletResponse response) throws IOException {
        List<Student> userList = getStudents();
        // 業(yè)務(wù)處理完成把數(shù)據(jù)寫到流中 響應(yīng)到頁面上
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" +
                new String("exportCsvFileTest.csv".getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
        response.setContentType(String.valueOf(StandardCharsets.UTF_8));
        CsvWriter csvWriter = CsvUtil.getWriter(response.getWriter());
        csvWriter.writeBeans(userList);
        csvWriter.close();
 
        return ResponseEntity.status(200).body("文件導(dǎo)出成功");
    }

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

相關(guān)文章

  • mybatis之調(diào)用帶輸出參數(shù)的存儲(chǔ)過程(Oracle)

    mybatis之調(diào)用帶輸出參數(shù)的存儲(chǔ)過程(Oracle)

    這篇文章主要介紹了mybatis調(diào)用帶輸出參數(shù)的存儲(chǔ)過程(Oracle),具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • Java語言----三種循環(huán)語句的區(qū)別介紹

    Java語言----三種循環(huán)語句的區(qū)別介紹

    下面小編就為大家?guī)硪黄狫ava語言----三種循環(huán)語句的區(qū)別介紹。小編舉得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2016-07-07
  • MyBatis-Plus?UserMpper接口示例實(shí)現(xiàn)

    MyBatis-Plus?UserMpper接口示例實(shí)現(xiàn)

    本文主要介紹了MyBatis-Plus?UserMpper接口示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2025-09-09
  • 詳解Maven POM(項(xiàng)目對象模型)

    詳解Maven POM(項(xiàng)目對象模型)

    這篇文章主要介紹了Maven POM(項(xiàng)目對象模型)的相關(guān)資料,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-07-07
  • Java實(shí)現(xiàn)EasyCaptcha圖形驗(yàn)證碼的具體使用

    Java實(shí)現(xiàn)EasyCaptcha圖形驗(yàn)證碼的具體使用

    Java圖形驗(yàn)證碼,支持gif、中文、算術(shù)等類型,可用于Java Web、JavaSE等項(xiàng)目,下面就跟隨小編一起來了解一下
    2021-08-08
  • Spring如何使用@Indexed加快啟動(dòng)速度

    Spring如何使用@Indexed加快啟動(dòng)速度

    這篇文章主要介紹了Spring如何使用@Indexed加快啟動(dòng)速度,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • 如何基于http代理解決Java固定ip問題

    如何基于http代理解決Java固定ip問題

    這篇文章主要介紹了如何基于http代理解決Java固定ip問題,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-03-03
  • springBoot3 生成訂單號(hào)的示例代碼

    springBoot3 生成訂單號(hào)的示例代碼

    本文主要介紹了springBoot3 生成訂單號(hào)的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2025-10-10
  • Java 二維碼,QR碼,J4L-QRCode 的資料整理

    Java 二維碼,QR碼,J4L-QRCode 的資料整理

    本文主要介紹Java 中二維碼,QR碼,J4L-QRCode,這里整理了詳細(xì)的資料供大家學(xué)習(xí)參考關(guān)于二維碼的知識(shí),有需要的小伙伴可以參考下
    2016-08-08
  • 一文帶你搞懂Java中泛型符號(hào)T,E,K,V,?的區(qū)別

    一文帶你搞懂Java中泛型符號(hào)T,E,K,V,?的區(qū)別

    泛型是Java中一個(gè)非常重要的內(nèi)容,這篇文章主要介紹了Java泛型中T、E、K、V、?的符號(hào)含義與區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2025-10-10

最新評論

华安县| 金昌市| 沧州市| 台湾省| 黑龙江省| 柳河县| 清原| 恩平市| 汉寿县| 新晃| 木兰县| 陕西省| 汉川市| 西藏| 开化县| 隆子县| 乳源| 扬州市| 铜梁县| 瑞金市| 黎川县| 钟祥市| 宁夏| 奉新县| 南京市| 邯郸县| 陇西县| 玛多县| 洞口县| 卢氏县| 林州市| 新河县| 蓬安县| 集安市| 遂宁市| 濮阳县| 灵台县| 霍邱县| 常德市| 镇远县| 鄂伦春自治旗|