SpringBoot整合easyExcel實現(xiàn)CSV格式文件的導入導出
更新時間:2024年02月25日 14:15:07 作者:夏林夕
這篇文章主要為大家詳細介紹了SpringBoot整合easyExcel實現(xiàn)CSV格式文件的導入導出,文中的示例代碼講解詳細,具有一定的參考價值,感興趣的小伙伴可以參考下
一: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())) { // 獲取標題 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ā)生異常,認為格式不正確 return false; } // 所有檢查都通過,則認為格式正確 return true; } }
三:Web端進行測試
/** * @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("文件讀取出錯"); } // 處理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() { // 創(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工具類來進行導出功能
/** * 使用 hutool 工具類生成一個csv格式的文檔 * * @param response * @return * @throws IOException */ @GetMapping("/exportCsvHutool") public ResponseEntity<?> exportCsvHutool(HttpServletResponse response) throws IOException { List<Student> userList = getStudents(); // 業(yè)務處理完成把數(shù)據(jù)寫到流中 響應到頁面上 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("文件導出成功"); }
以上就是SpringBoot整合easyExcel實現(xiàn)CSV格式文件的導入導出的詳細內(nèi)容,更多關于SpringBoot easyExcel CSV導入導出的資料請關注腳本之家其它相關文章!
您可能感興趣的文章:
- SpringBoot?整合?EasyExcel?實現(xiàn)自由導入導出功能
- SpringBoot整合EasyExcel實現(xiàn)批量導入導出
- SpringBoot整合EasyExcel實現(xiàn)復雜Excel表格的導入導出
- 使用SpringBoot與EasyExcel實現(xiàn)復雜的導入導出
- SpringBoot整合EasyExcel實現(xiàn)導入導出功能
- SpringBoot中EasyExcel實現(xiàn)execl導入導出
- SpringBoot整合EasyExcel實現(xiàn)導入導出數(shù)據(jù)
- SpringBoot整合EasyExcel實現(xiàn)文件導入導出
- Springboot整合easyexcel實現(xiàn)一個接口任意表的Excel導入導出
相關文章
Java Map 按key排序和按Value排序的實現(xiàn)方法
下面小編就為大家?guī)硪黄狫ava Map 按key排序和按Value排序的實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08SpringBoot整合Mybatis-Plus+Druid實現(xiàn)多數(shù)據(jù)源配置功能
本文主要講解springboot?+mybatisplus?+?druid?實現(xiàn)多數(shù)據(jù)源配置功能以及一些必要的準備及代碼說明,具有一定的參考價值,感興趣的小伙伴可以借鑒一下2023-06-06Java基礎篇之serialVersionUID用法及注意事項詳解
這篇文章主要給大家介紹了關于Java基礎篇之serialVersionUID用法及注意事項的相關資料,SerialVersionUID屬性是用于序列化/反序列化可序列化類的對象的標識符,我們可以用它來記住可序列化類的版本,以驗證加載的類和序列化對象是否兼容,需要的朋友可以參考下2024-02-02