ExcelUtils实现excel导入
时间: 2023-07-07 18:04:37 浏览: 69
ExcelUtils是一个常用的Java工具类,可以用于实现excel导入。以下是实现步骤:
1. 首先需要引入poi和poi-ooxml依赖:
```xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
```
2. 定义ExcelUtils工具类,实现导入方法:
```java
public class ExcelUtils {
public static List<List<String>> readExcel(File file) throws IOException {
List<List<String>> result = new ArrayList<>();
Workbook workbook = WorkbookFactory.create(file);
Sheet sheet = workbook.getSheetAt(0);
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
List<String> rowList = new ArrayList<>();
for (int j = 0; j < row.getLastCellNum(); j++) {
Cell cell = row.getCell(j);
if (cell == null) {
rowList.add("");
} else {
rowList.add(cell.toString());
}
}
result.add(rowList);
}
return result;
}
}
```
3. 调用ExcelUtils读取excel文件:
```java
File file = new File("path/to/file.xlsx");
List<List<String>> result = ExcelUtils.readExcel(file);
```
其中,result是一个二维List,每一行代表excel文件中的一行数据,每一列代表对应行的一个单元格数据。可以根据需要对result进行进一步处理。