帮我写一段代码,实现excel导入,分别给出controller,service,层
时间: 2023-10-09 12:17:35 浏览: 51
Controller层:
```java
@RestController
@RequestMapping("/api/excel")
public class ExcelController {
@Autowired
private ExcelService excelService;
@PostMapping("/import")
public ResponseEntity<String> importExcel(@RequestParam("file") MultipartFile file) {
try {
excelService.importExcel(file);
return ResponseEntity.ok("Excel导入成功!");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Excel导入失败:" + e.getMessage());
}
}
}
```
Service层:
```java
@Service
public class ExcelService {
@Autowired
private UserRepository userRepository;
public void importExcel(MultipartFile file) throws Exception {
List<User> userList = new ArrayList<>();
Workbook workbook = WorkbookFactory.create(file.getInputStream());
Sheet sheet = workbook.getSheetAt(0); //获取第一个Sheet页
for (int i = 1; i <= sheet.getLastRowNum(); i++) { //遍历行
Row row = sheet.getRow(i);
String name = row.getCell(0).getStringCellValue();
int age = (int) row.getCell(1).getNumericCellValue();
String gender = row.getCell(2).getStringCellValue();
Date birthday = row.getCell(3).getDateCellValue();
User user = new User(name, age, gender, birthday);
userList.add(user);
}
userRepository.saveAll(userList);
}
}
```
Repository层:
```java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
```
注:以上代码使用了Spring Boot、Spring Data JPA、Apache POI等框架和工具类。其中,User为实体类,包含name、age、gender、birthday等属性和对应的getter/setter方法。