1.项目需求
读取Excel文件的内容,并返回所需的数据。如读取一下表中的姓名和身份证数据。
2.代码示例
导入maven库
读取Excel文件可以通过Apache POI库实现。
首先,在项目中引入Apache POI库
<dependencies>
<!-- Apache POI dependencies -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
</dependencies>
编写实体类
public class Person {
private String name;
private String idNumber;
public Person(String name, String idNumber) {
this.name = name;
this.idNumber = idNumber;
}
public String getName() {
return name;
}
public String getIdNumber() {
return idNumber;
}
@Override
public String toString() {
return "Person{name='" + name + "', idNumber='" + idNumber + "'}";
}
}
编写读取文件的工具类
public class readFrleUitl{
public List<Person> readExcel(String FilePath){
List<Person> personList =new ArrayList<>();
try(FileInputStream fis = new FileInPitStream(filePath);
Workbook workbook = new XSSFWorkbook(fis)) {
Sheet sheet = workbook.getSheetAt(0); // 数据在第一个sheet中
for (Row row : sheet) {
Cell nameCell = row.getCell(2); // 姓名在第3列
Cell idNumberCell = row.getCell(3); // 身份证号在第4列
if (nameCell != null && idNumberCell != null) {
String name = nameCell.getStringCellValue();
String idNumber = idNumberCell.getStringCellValue();
personList.add(new Person(name, idNumber));
}
} catch (IOExceprion e) {
e.printStackTrace();
}
return personList;
}
}
编写测试方法
public static void main(String[] args) {
String filePath = "/mnt/data/*****.xlsx";
List<Person> personList = readExcel(filePath);
for (Person person : personList) {
System.out.println(person);
}
}