springboot读取和写入csv文件数据
在Spring Boot中,你可以使用opencsv
库来读写CSV文件。以下是一个简单的例子:
- 添加依赖到你的
pom.xml
:
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.2</version>
</dependency>
- 创建一个映射CSV文件的实体类:
import com.opencsv.bean.CsvBindByName;
public class MyCsvBean {
@CsvBindByName
private String column1;
@CsvBindByName
private String column2;
// 标准的getter和setter
// ...
}
- 读取CSV文件:
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class CsvReader {
public List<MyCsvBean> readCsv(String filePath) {
try (Reader reader = Files.newBufferedReader(Paths.get(filePath))) {
CsvToBean<MyCsvBean> csvToBean = new CsvToBeanBuilder<MyCsvBean>(reader)
.withType(MyCsvBean.class)
.build();
return csvToBean.parse();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
- 写入CSV文件:
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class CsvWriter {
public void writeCsv(String filePath, List<MyCsvBean> data) {
try (Writer writer = Files.newBufferedWriter(Paths.get(filePath))) {
StatefulBeanToCsv<MyCsvBean> beanToCsv = new StatefulBeanToCsvBuilder<MyCsvBean>(writer)
.withQuoteChar('"')
.build();
beanToCsv.write(data);
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 使用读写方法:
public class CsvApp {
public static void main(String[] args) {
CsvReader csvReader = new CsvReader();
List<MyCsvBean> readData = csvReader.readCsv("path/to/input.csv");
// 处理读取的数据
// ...
CsvWriter csvWriter = new CsvWri
评论已关闭