Spring框架实现Excel批量导入数据
时间: 2024-02-24 18:53:55 浏览: 193
在Spring框架中,可以使用Apache POI库实现Excel批量导入数据。以下是一些实现步骤:
1. 添加依赖:在Maven或Gradle中添加Apache POI库的依赖,例如:
```
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
```
2. 创建Excel文件读取对象:使用WorkbookFactory类创建Excel文件读取对象,例如:
```
File file = new File("data.xlsx");
Workbook workbook = WorkbookFactory.create(file);
Sheet sheet = workbook.getSheetAt(0);
```
3. 遍历Excel表格数据:使用Sheet和Row类遍历Excel表格中的数据,例如:
```
for (Row row : sheet) {
String name = row.getCell(0).getStringCellValue();
int age = (int) row.getCell(1).getNumericCellValue();
// ...
}
```
4. 将数据导入数据库:使用Spring的JdbcTemplate类将数据导入数据库,例如:
```
jdbcTemplate.update("INSERT INTO person (name, age) VALUES (?, ?)", name, age);
```
完整代码示例:
```
import java.io.File;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component
public class ExcelImporter {
@Autowired
private JdbcTemplate jdbcTemplate;
public void importData() throws IOException {
File file = new File("data.xlsx");
Workbook workbook = WorkbookFactory.create(file);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
String name = row.getCell(0).getStringCellValue();
int age = (int) row.getCell(1).getNumericCellValue();
jdbcTemplate.update("INSERT INTO person (name, age) VALUES (?, ?)", name, age);
}
}
}
```
在Spring中,可以将ExcelImporter类注入到其他类中使用,例如:
```
@Autowired
private ExcelImporter excelImporter;
public void doImport() throws IOException {
excelImporter.importData();
}
```
阅读全文