文章目录
-
-
- [一、Maven 引入](#一、Maven 引入)
- 二、代码实现
-
一、Maven 引入
xml
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-csv -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.8</version>
</dependency>
二、代码实现
java
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ReadCsvNW {
public static void main(String[] args) {
try {
InputStream inputStream = Files.newInputStream(Paths.get("D:\\Documents\\2024-06-16.zip"));
ZipInputStream zis = new ZipInputStream(inputStream);
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (!entry.isDirectory() && entry.getName().endsWith(".csv")) {
BufferedReader reader = new BufferedReader(new InputStreamReader(zis, "GBK"));
CSVParser csvParser = new CSVParser(reader, CSVFormat.EXCEL.withFirstRecordAsHeader());
if (entry.getName().equals("hehe.csv")) {
for (CSVRecord record : csvParser) {
// 方式一:通过下角标获取值
System.out.println("数据行:" + record.get(5));
// 方式一:通过表头列名获取值
System.out.println("数据行:" + record.get("name"));
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}