在項(xiàng)目的開(kāi)發(fā)工程中,經(jīng)常有導(dǎo)入導(dǎo)出的功能場(chǎng)景,之前一直用的是Apache的POI但是其原生的用法太復(fù)雜,基本都是在網(wǎng)上copy + debug 一天實(shí)習(xí)生說(shuō)SpringBoot 集成 EasyPoi簡(jiǎn)單的很,幾句話就搞定了。SO 學(xué)習(xí)了一下EasyPoi
EasyPoi簡(jiǎn)介
試用了一下easypoi很簡(jiǎn)單就可以實(shí)現(xiàn)Excel導(dǎo)出,Excel模板導(dǎo)出,Excel導(dǎo)入,過(guò)簡(jiǎn)單的注解就可以替代以前復(fù)雜的代碼。
非常契合基于注解開(kāi)發(fā)的思想。
具體的介紹和使用文檔可以參考官方鏈接:
官方文檔:http://doc.wupaas.com/docs/easypoi/easypoi-1c0u96flii98v
使用
1: 添加maven依賴
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.4.0</version>
</dependency>
2: 創(chuàng)建EXCEL導(dǎo)入類
使用方式很簡(jiǎn)單就是在我們的VO 類的成員變量上添加@EXCEL 注解同時(shí)指定好對(duì)應(yīng)的EXCEL title
@Data
public class UserInfoBody {
@Excel(name = "name")
private String name;
@Excel(name = "oldUserId")
private String oldUserId;
@Excel(name = "newUserId")
private String newUserId;
@Excel(name = "mobile")
private String mobile;
}
3: 創(chuàng)建controller層
@RestController
@RequestMapping("/userInfo”)
public class UserInfoController {
@Autowired
private UserInfoService userInfoService;
@PostMapping("/excel/upload")
public void uploadUserInfo(@RequestParam(value = "file") MultipartFile multipartFile) {
userInfoService.UserInfoUpload(multipartFile);
}
}
4: 創(chuàng)建service層
@Service
public class UserInfoServiceImpl implements UserInfoService {
private <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
if (file == null){
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows); //excel 的title 是從那一行開(kāi)始的
params.setHeadRows(headerRows); //title 總共有幾行,如果設(shè)置為2, 則會(huì)將第一行與第二行逐列拼接起來(lái)作為title([0,0]_[0,1])
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params); //ExcelImportUtil.importExcel 是easypoi提供的excel解析工具類
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
private void doUserInfoUpload(List<UserIDUpdateBody> userIDs) {
userIDs.stream().filter(x -> StringUtils.hasLength(x.getOldUserId())).forEach(u -> {
System.out.println("name:" + u.getName() + "oldId: " + u.getOldUserId() + "newId: " + u.getNewUserId());
});
}
@Override
public void UserInfoUpload(MultipartFile multipartFile) {
List<UserInfoBody> userInfos = importExcel(multipartFile, 0, 1, UserInfoBody.class);
if (!ObjectUtils.isEmpty(userInfos)) {
doUserInfoUpload(userInfos);
}
}
}
5: 測(cè)試
基本上的代碼就編寫完了,使用postman開(kāi)始測(cè)試

image.png

image.png
name:小紅oldId: xiaohong newId:xiaohong1
name:小明oldId: xiaoming newId:xiaoming1