目录
一:pom依赖
二:检查CSV内容格式的工具类
三:Web端进行测试
四:拓展使用文章来源:https://www.toymoban.com/news/detail-785067.html
一: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工具类来进行导出功能文章来源地址https://www.toymoban.com/news/detail-785067.html
/**
* 使用 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("文件导出成功");
}
到了这里,关于SpringBoot整合easyExcel实现CSV格式文件的导入导出的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!