springboot按照要求将excel文件的数据导入数据库
时间: 2024-05-06 21:19:11 浏览: 87
Springboot上传excel并将表格数据导入或更新mySql数据库的过程
好的,你需要使用Apache POI这个Java库来读取Excel文件的数据,然后使用JDBC将数据插入到数据库中。以下是一个简单的示例代码:
1. 首先,您需要在pom.xml中添加以下依赖项:
```xml
<dependencies>
<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>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
</dependencies>
```
2. 接下来,您需要编写一个类来读取Excel文件并将其转换为Java对象。以下是一个示例方法:
```java
public List<Employee> readEmployeesFromExcelFile(String filePath) throws IOException {
FileInputStream fis = new FileInputStream(new File(filePath));
Workbook workbook = new XSSFWorkbook(fis); // 读取XLSX文件
Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
List<Employee> employees = new ArrayList<>();
for (int i = 1; i <= sheet.getLastRowNum(); i++) { // 从第二行开始循环,因为第一行是标题行
Row row = sheet.getRow(i);
Employee employee = new Employee();
employee.setName(row.getCell(0).getStringCellValue());
employee.setAge((int) row.getCell(1).getNumericCellValue());
employee.setSalary(row.getCell(2).getNumericCellValue());
employees.add(employee);
}
workbook.close();
fis.close();
return employees;
}
```
3. 然后,您需要编写一个将Java对象插入到数据库中的方法。以下是一个示例方法:
```java
public void insertEmployees(List<Employee> employees) throws SQLException {
String sql = "INSERT INTO employee (name, age, salary) VALUES (?, ?, ?)";
Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
for (Employee employee : employees) {
stmt.setString(1, employee.getName());
stmt.setInt(2, employee.getAge());
stmt.setDouble(3, employee.getSalary());
stmt.executeUpdate();
}
stmt.close();
conn.close();
}
```
4. 最后,您可以编写一个控制器方法来调用这些方法:
```java
@PostMapping("/import")
public ResponseEntity<String> importData(@RequestParam("file") MultipartFile file) {
try {
List<Employee> employees = readEmployeesFromExcelFile(file.getInputStream());
insertEmployees(employees);
return ResponseEntity.ok("Data imported successfully!");
} catch (IOException | SQLException ex) {
ex.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while importing data.");
}
}
```
请注意,您需要将此代码适应您的数据模型和数据库架构。
阅读全文