在上一节的基础上,本文演示下如何导入excel数据。
Excel导入操作指导
- 继承ocean-easyexcel SDK,上一节打包生成
<dependency>
<groupId>com.angel.ocean</groupId>
<artifactId>ocean-easyexcel</artifactId>
<version>1.0.0</version>
</dependency>
- 定义Excel数据导入模型
package com.angel.ocean.domain.dto;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
/**
* Excel导入数据结构样例
*/
@Data
public class UserDataImportDTO {
@ExcelProperty("用户名")
private String username;
@ExcelProperty("密码")
private String password;
@ExcelProperty("注册时间")
private String createTime;
}
- 定义Excel数据导入业务类UserDataImportService,实现ExcelImportDataHandler,对导入数据进行处理
package com.angel.ocean.service;
import com.angel.ocean.domain.dto.UserDataImportDTO;
import com.angel.ocean.excel.ExcelImportDataHandler;
import java.util.List;
public class UserDataImportService implements ExcelImportDataHandler<UserDataImportDTO> {
private UserService userService;
public UserDataImportService(UserService userService) {
this.userService = userService;
}
@Override
public void handler(List<UserDataImportDTO> data) {
userService.excelImport(data);
}
}
package com.angel.ocean.service;
import com.alibaba.fastjson2.JSON;
import com.angel.ocean.domain.dto.UserDataImportDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;
@Slf4j
@Service
public class UserService {
public void excelImport(List<UserDataImportDTO> data) {
log.info("{}", JSON.toJSONString(data));
}
}
- 定义Excel数据导入业务接口
@PostMapping("import")
public ApiResult<?> importExcel(@RequestParam("file") MultipartFile file) throws IOException {
InputStream inputStream = file.getInputStream();
Integer sheetNo = 0;
Integer headRowNumber = 1;
ExcelImportDataHandler excelImportDataHandler = new UserDataImportService(userService);
EasyExcelUtil.readExcel(excelImportDataHandler, inputStream, UserDataImportDTO.class, sheetNo, headRowNumber);
return ApiResult.success();
}
Excel导入结果
需要导入Excel数据截图,总共16条数据:
Excel导入接口演示:
服务端导入数据打印信息,可以看出16条数据,分两批入库。