easypoi导入后转化为List
时间: 2024-10-15 09:15:20 浏览: 20
C#excel导入
Easypoi是一个用于操作Excel的开源Java库,它可以帮助你在Java程序中方便地读取、写入和处理Excel文件。如果你想要将Excel数据转换为List,通常的做法是先通过`EasyPoi`的`XSSFWorkbook`和`Sheet`类加载工作表,然后遍历每一行数据,将其存储为自定义的对象实例并添加到List中。
例如,假设有一个名为`User`的简单POJO类,代表Excel表格中的用户信息:
```java
public class User {
private String name;
private int age;
// getters and setters...
}
```
你可以按照以下步骤将Excel数据转换为List<User>:
```java
import org.apache.poi.ss.usermodel.*;
import java.util.List;
import java.util.ArrayList;
// ...
List<User> userList = new ArrayList<>();
try (Workbook workbook = new XSSFWorkbook(file.getInputStream());
Sheet sheet = workbook.getSheetAt(0)) {
for (Row row : sheet) {
if (row.getRowNum() == 0) { // 忽略标题行
continue;
}
User user = new User();
Cell nameCell = row.getCell(0);
Cell ageCell = row.getCell(1);
if (nameCell != null && !nameCell.getStringCellValue().isEmpty()) {
user.setName(nameCell.getStringCellValue());
}
if (ageCell != null && ageCell.getCellType() == CellType.NUMERIC) {
user.setAge((int) ageCell.getNumericCellValue());
}
userList.add(user);
}
} catch (IOException e) {
e.printStackTrace();
}
// Now, userList contains the data from the Excel file as a list of User objects.
阅读全文