官方文档指南:
https://commons.apache.org/proper/commons-csv/user-guide.html
添加依赖:
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-csv -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.6</version>
</dependency>
案例:
package com.lcf;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.Date;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import org.junit.Test;
/**
* @author : lichenfei
* @date : 2019年3月18日
* @time : 下午2:12:20
*
*/
public class CsvDemo {
// 官方文档: https://commons.apache.org/proper/commons-csv/user-guide.html
/**
* 写入
*
* @author : lichenfei
* @throws IOException
* @date : 2019年3月18日
* @time : 下午2:13:31
*
*/
@Test
public void write() throws IOException {
File file = new File("C:/Users/John/Desktop");
if (!file.exists()) {
file.mkdirs();
}
Appendable printWriter = new PrintWriter(file + "/CSV-TEST.CSV");
CSVPrinter csvPrinter = CSVFormat.EXCEL.withHeader("姓名", "性别", "年龄", "生日").print(printWriter);
for (int i = 0; i < 10; i++) {
csvPrinter.printRecord("lcf" + i, "M" + i, 18 + i, new Date());
}
csvPrinter.flush();
csvPrinter.close();
}
/**
* 读取(按索引访问列值)
*
* @author : lichenfei
* @throws IOException
* @date : 2019年3月18日
* @time : 下午2:13:21
*
*/
@Test
public void readOne() throws IOException {
Reader reader = new FileReader("C:/Users/John/Desktop/CSV-TEST.CSV");
Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(reader);
for (CSVRecord csvRecord : records) {
System.out.println(
csvRecord.get(0) + "---" + csvRecord.get(1) + "---" + csvRecord.get(2) + "---" + csvRecord.get(3));
}
reader.close();
}
/**
* 读取(手动定义标头访问列值)
*
* @author : lichenfei
* @throws IOException
* @date : 2019年3月18日
* @time : 下午2:13:21
*
*/
@Test
public void readTwo() throws IOException {
Reader reader = new FileReader("C:/Users/John/Desktop/CSV-TEST.CSV");
Iterable<CSVRecord> records = CSVFormat.RFC4180.withHeader("name", "sex", "age", "birthday").parse(reader);
for (CSVRecord csvRecord : records) {
System.out.println(csvRecord.get("name") + "---" + csvRecord.get("sex") + "---" + csvRecord.get("age")
+ "---" + csvRecord.get("birthday"));
}
reader.close();
}
/**
* 读取(标头自动检测访问列值)
*
* @author : lichenfei
* @throws IOException
* @date : 2019年3月18日
* @time : 下午2:13:21
*
*/
@Test
public void readThree() throws IOException {
Reader reader = new FileReader("C:/Users/John/Desktop/CSV-TEST.CSV");
Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(reader);// 定义后必须和csv文件中的标头一致
for (CSVRecord csvRecord : records) {// 第一行不会被打印出来
System.out.println(csvRecord.get("姓名") + "---" + csvRecord.get("性别") + "---" + csvRecord.get("年龄") + "---"
+ csvRecord.get("生日"));
}
reader.close();
}
}
写入后的文件:
读取的数据: