SpringBoot整合easyExcel實(shí)現(xiàn)CSV格式文件的導(dǎo)入導(dǎo)出
一: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;
}
// 所有檢查都通過(guò),則認(rèn)為格式正確
return true;
}
}三:Web端進(jìn)行測(cè)試
/**
* @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ù)庫(kù)
*
* @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工具類來(lái)進(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)到頁(yè)面上
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)出的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- SpringBoot?整合?EasyExcel?實(shí)現(xiàn)自由導(dǎo)入導(dǎo)出功能
- SpringBoot整合EasyExcel實(shí)現(xiàn)批量導(dǎo)入導(dǎo)出
- SpringBoot整合EasyExcel實(shí)現(xiàn)復(fù)雜Excel表格的導(dǎo)入導(dǎo)出
- 使用SpringBoot與EasyExcel實(shí)現(xiàn)復(fù)雜的導(dǎo)入導(dǎo)出
- SpringBoot整合EasyExcel實(shí)現(xiàn)導(dǎo)入導(dǎo)出功能
- SpringBoot中EasyExcel實(shí)現(xiàn)execl導(dǎo)入導(dǎo)出
- SpringBoot整合EasyExcel實(shí)現(xiàn)導(dǎo)入導(dǎo)出數(shù)據(jù)
- SpringBoot整合EasyExcel實(shí)現(xiàn)文件導(dǎo)入導(dǎo)出
- Springboot整合easyexcel實(shí)現(xiàn)一個(gè)接口任意表的Excel導(dǎo)入導(dǎo)出
相關(guān)文章
Java Map 按key排序和按Value排序的實(shí)現(xiàn)方法
下面小編就為大家?guī)?lái)一篇Java Map 按key排序和按Value排序的實(shí)現(xiàn)方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-08-08
解決Nacos集群?jiǎn)?dòng)失敗:java版本問(wèn)題
這篇文章主要介紹了解決Nacos集群?jiǎn)?dòng)失敗:java版本問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06
SpringBoot整合Mybatis-Plus+Druid實(shí)現(xiàn)多數(shù)據(jù)源配置功能
本文主要講解springboot?+mybatisplus?+?druid?實(shí)現(xiàn)多數(shù)據(jù)源配置功能以及一些必要的準(zhǔn)備及代碼說(shuō)明,具有一定的參考價(jià)值,感興趣的小伙伴可以借鑒一下2023-06-06
Mybatis-plus原生pages分頁(yè)未生效的解決方案
本文主要介紹了Mybatis-plus原生pages分頁(yè)未生效的解決方案,包含介紹了未生效的5種原因以及解決方法,具有一定的參考價(jià)值,感興趣的可以了解一下2024-07-07
Java基礎(chǔ)篇之serialVersionUID用法及注意事項(xiàng)詳解
這篇文章主要給大家介紹了關(guān)于Java基礎(chǔ)篇之serialVersionUID用法及注意事項(xiàng)的相關(guān)資料,SerialVersionUID屬性是用于序列化/反序列化可序列化類的對(duì)象的標(biāo)識(shí)符,我們可以用它來(lái)記住可序列化類的版本,以驗(yàn)證加載的類和序列化對(duì)象是否兼容,需要的朋友可以參考下2024-02-02
Java Web項(xiàng)目中編寫定時(shí)任務(wù)的實(shí)現(xiàn)
本篇文章主要介紹了Java Web項(xiàng)目中編寫定時(shí)任務(wù)的實(shí)現(xiàn),具有一定的參考價(jià)值,有興趣的可以了解一下。2017-01-01

