目录
一:pom依赖
三:Web端进行测试
四:拓展使用
org.apache.poi poi4.1.2 org.apache.poi poi-ooxml4.1.2 org.apache.poi poi-ooxml-schemas4.1.2 org.apache.commons commons-compress1.21 org.apache.poi ooxml-schemas1.4 com.alibaba easyexcel3.1.1 org.slf4j slf4j-log4j121.7.26 test org.apache.commons commons-csv1.9.0 com.opencsv opencsv5.6 com.alibaba fastjson1.2.73
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())) { // 获取标题 Listheaders = 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; } }
/** * @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) { ListuserList = new CopyOnWriteArrayList<>(); try { EasyExcel.read(file.getInputStream(), User.class, new PageReadListener (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 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 getStudents() { // 创建数据列表 List 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 { ListuserList = 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("文件导出成功"); }