springboot实现excel文件存储到mysql
时间: 2023-11-26 22:06:41 浏览: 75
实现将Excel文件存储到MySQL数据库,可以按照以下步骤进行:
1. 创建一个Spring Boot项目,并添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<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. 创建一个Java类,用于实现Excel文件读取和数据存储到MySQL数据库操作,如下所示:
```
@Component
public class ExcelService {
private final UserRepository userRepository;
@Autowired
public ExcelService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public void saveExcelToDb(MultipartFile file) throws IOException {
Workbook workbook = new XSSFWorkbook(file.getInputStream());
Sheet sheet = workbook.getSheetAt(0);
List<User> users = new ArrayList<>();
for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
Row row = sheet.getRow(i);
if (row != null) {
User user = new User();
user.setName(row.getCell(0).getStringCellValue());
user.setAge((int) row.getCell(1).getNumericCellValue());
user.setEmail(row.getCell(2).getStringCellValue());
users.add(user);
}
}
userRepository.saveAll(users);
}
}
```
3. 创建一个实体类User,用于映射数据库表。
```
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int age;
private String email;
// getter and setter methods
}
```
4. 创建一个接口UserRepository,用于操作数据库。
```
public interface UserRepository extends JpaRepository<User, Long> {
}
```
5. 创建一个Controller类,用于接收上传的Excel文件,并调用ExcelService中的saveExcelToDb方法将数据存储到MySQL数据库。
```
@RestController
@RequestMapping("/api")
public class ExcelController {
private final ExcelService excelService;
@Autowired
public ExcelController(ExcelService excelService) {
this.excelService = excelService;
}
@PostMapping("/upload")
public ResponseEntity<String> uploadExcelFile(@RequestParam("file") MultipartFile file) {
try {
excelService.saveExcelToDb(file);
return ResponseEntity.ok("File uploaded successfully!");
} catch (IOException e) {
return ResponseEntity.badRequest().body("Could not upload the file: " + file.getOriginalFilename() + "!");
}
}
}
```
以上就是将Excel文件存储到MySQL数据库的实现方法。
阅读全文