SpringBoot整合easyExcel实现CSV格式文件的导入导出

2023-12-13 03:27:36

目录

一:pom依赖

二:检查CSV内容格式的工具类

三:Web端进行测试

四:拓展使用


一: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内容格式的工具类

checkCscUtils.java
package com.example.juc.test.Controller;

/**
 * @Author 
 * @Date Created in  2023/12/5 17:32
 * @DESCRIPTION:  判断csv 文件内容是否正确
 * @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())) {
            // 获取标题
            List<String> headers = parser.getHeaderNames();
            int numberOfColumns = headers.size();

            for (CSVRecord record : parser) {
                // 检查列数是否一致
                if (record.size() != numberOfColumns) {
                    return false;
                }
                // 这里可以添加更多的检查,例如检查数据类型等
            }
        } catch (IOException e) {
            e.printStackTrace();
            // 如果发生异常,认为格式不正确
            return false;
        }
        // 所有检查都通过,则认为格式正确
        return true;
    }
}

三:Web端进行测试



/**
 * @Author 
 * @Date Created in  2023/11/2 10:59
 * @DESCRIPTION: 读取csv格式的文件数据
 * @Version V1.0
 */

@RestController
@RequestMapping("/api/csv")
public class CsvController {

    /**
     * 读取传入的csv  文本的内容可以存入数据库
     *
     * @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文件格式内容是否有误?
        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("文件读取出错");
            }

            // 处理userList...

            return ResponseEntity.ok(userList);
        }
        return ResponseEntity.status(500).body("文件格式出错");
    }

    /**
     * 使用 easyExcel  导出一个csv 格式,但是版本可能与poi 版本冲突
     *
     * @param response
     * @return
     * @throws IOException
     */
    @GetMapping("/exportCsv")
    public ResponseEntity<?> exportCsv(HttpServletResponse response) throws IOException {
        // 设置响应头
        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导出CSV文件response.getOutputStream()
        try {
            EasyExcel.write(response.getOutputStream(), Student.class)
                    .excelType(ExcelTypeEnum.CSV)
                    .sheet("我的学生")
                    .doWrite(userList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResponseEntity.status(200).body("文件导出成功");
    }



 


    private static List<Student> getStudents() {
        // 创建数据列表
        List<Student> userList = new CopyOnWriteArrayList<>();
        // 添加数据(示例)
        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工具类来进行导出功能

    /**
     * 使用 hutool 工具类生成一个csv格式的文档
     *
     * @param response
     * @return
     * @throws IOException
     */
    @GetMapping("/exportCsvHutool")
    public ResponseEntity<?> exportCsvHutool(HttpServletResponse response) throws IOException {
        List<Student> userList = getStudents();
        // 业务处理完成把数据写到流中 响应到页面上
        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("文件导出成功");
    }

文章来源:https://blog.csdn.net/XikYu/article/details/134861196
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。