spingboot解析CSV文件
- 导入opencsv库:将opencsv库添加到项目的依赖中。
<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>5.3</version> </dependency>
- 创建MappingStrategy对象:创建一个实现MappingStrategy接口的Java类来描述CSV文件中的数据格式,并创建MappingStrategy对象。
Name,Email,Phone John Doe,john.doe@example.com,123-456-7890 Jane Doe,jane.doe@example.com,987-654-3210
那么可以创建一个Person类来描述CSV文件中的每一行数据,并实现MappingStrategy接口来将CSV文件中的每一行数据映射到Person对象中。
public class Person { private String name; private String email; private String phone; // getters and setters } public class PersonMappingStrategy extends HeaderColumnNameMappingStrategy<Person> { @Override public Person createBean() throws InstantiationException, IllegalAccessException { return new Person(); } }
- 在Spring Boot的配置类中配置MultipartResolver:在Spring Boot应用程序的配置类中,配置MultipartResolver来处理MultipartFile上传的文件。
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.multipart.commons.CommonsMultipartResolver; @Configuration public class AppConfig { @Bean public CommonsMultipartResolver multipartResolver() { CommonsMultipartResolver resolver = new CommonsMultipartResolver(); resolver.setDefaultEncoding("utf-8"); resolver.setMaxUploadSize(1024 * 1024 * 10); // 设置上传文件的最大大小为10MB return resolver; } }
- 创建Controller类来处理上传文件:创建一个Controller类,使用@RequestBody注解将上传的MultipartFile对象转换为File对象,然后使用CsvToBeanBuilder将文件中的数据映射到Java对象中。
import com.opencsv.bean.CsvToBean; import com.opencsv.bean.CsvToBeanBuilder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.multipart.MultipartFile; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; @Controller public class FileUploadController { @PostMapping("/upload") public String uploadFile(@RequestBody MultipartFile file) throws IOException { // 将MultipartFile对象转换为File对象 File csvFile = File.createTempFile("temp", ".csv"); file.transferTo(csvFile); // 创建MappingStrategy对象和CsvToBean对象 MappingStrategy<Person> strategy = new PersonMappingStrategy(); CsvToBean<Person> csvToBean = new CsvToBeanBuilder<Person>(new BufferedReader(new InputStreamReader(file.getInputStream()))) .withMappingStrategy(strategy) .withType(Person.class) .build(); // 读取CSV文件数据 List<Person> personList = csvToBean.parse(); // Do something with personList return "redirect:/"; } }