Nối tiếp phần 1 mình đã hướng dẫn các bạn tạo abstract class và validator dùng chung. Các bạn có thể xem tại đây:
How To Import Excel Spring Boot – Trả Lỗi Trong File
Import Excel Spring Boot In Java
Khởi tạo class DTO
Đầu tiên mình sẽ tạo class dto với các trường có trong file excel để nhận dữ liệu. Tất nhiên có DTO thì mình phải có cả entity class với 3 trường như dưới. Entity thì file tên là Excel.class với cá trường bên dưới mình không viết lại nha.
@Data
@NoArgsConstructor
@AllArgsConstructor
@DataExcelCheckDuplication
public class ExcelDTO {
public ExcelDTO (String code, String name) {
this.code = code;
this.name= name;
}
@ExcelCell(0)
@NotBlank(message = "name_empty")
@Size(max = 200, message = "name_validation_size")
public String name;
@ExcelCell(1)
@NotBlank(message = "code_empty")
@Size(max = 255, message = "code_validation_size")
public String code;
@ExcelCell(2)
@NotNull(message = "value_empty")
@Digits(integer = 9, fraction = 2, message = "value_invalid")
public BigDecimal value;
}

Tầng Controler
@PreAuthorize("hasAuthority('IMPORT_EXCEL')")
@PostMapping(value = "/importExcel", consumes = {"multipart/form-data"})
public ResponseEntity<?> importExcel(@RequestPart("file") MultipartFile file, HttpServletResponse response, Locale locale) {
if (!Constants.FILE_TYPE_ALLOWED.contains(file.getContentType())) {
// Trả ra thông báo lỗi file không đúng định dạng
}
excelService.importExcel(file, response, locale);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
Tầng Service
private final ModelMapper mapper;
private final ExcelRepository excelRepository;
private final MessageSource messageSource;
/**
* @param file
* @param response
* @param locale
*/
public void importExcel(MultipartFile file, HttpServletResponse response, Locale locale) {
ImportExcelValidator<ExcelDTO, Excel> excelValidator = new ExcelImportValidator(file, Constants.EXCEL_HEADER_START, locale, mapper, excelRepository, messageSource);
excelValidator.validatePre().thenReturnExcelIfError(response);
// Check validate and Save data
List<Excel> excels = excelValidator.validate().thenReturnExcelIfError(response).thenMappingAndReturnDestinationObjects();
}
Trong đó có 1 số cái các bạn cần để ý:
- Mình sẽ gọi abstract ImportExcelValidator.class ( bài trước đã viết để sử dụng )
- EXCEL_HEADER_START : Dòng bắt đầu trong excel, không tính dòng tiêu đề. Như ảnh file excel trên thì sẽ là dòng 2
- locale : là ngôn ngữ
Tầng Validator Import File Excel
Để xem chi tiết hơn thì các bạn ngâm cứu code trong github của mình nhé: https://github.com/nqt-tech/Import-Excel-Spring-Boot
Nếu các bạn có ý tưởng, code tối ưu hơn thì chia sẻ với mình để mình cập nhật thêm nhé.