- springboot:整合easypoi
- 一、导出
- pom文件
- 实体类
- 工具类
- service
- controller
- 导出结果
- 二、导入
- 普通导入
- controller 和service
- 导入结果
- 校验导入
- 修改实体类
- 自定义校验类
- controller和service
- 校验结果
springboot:整合easypoi 一、导出 pom文件easypoi的常用注解
easypoi的导入校验
项目源码
实体类cn.afterturn easypoi-spring-boot-starter 4.0.0 javax.validation validation-api 2.0.1.Final org.hibernate.validator hibernate-validator 6.0.16.Final compile com.hl springboot-common 0.0.1-SNAPSHOT org.springframework.boot spring-boot-starter-web
CourseEntity.java
@Data
@ExcelTarget("courseEntity")
public class CourseEntity {
private String id;
@Excel(name = "课程名称", orderNum = "0", width = 25, needMerge = true)
private String name;
@ExcelEntity(id = "absent")
private TeacherEntity mathTeacher;
@ExcelCollection(name = "学生", orderNum = "2")
private List students;
}
StudentEntity.java
@Data
public class StudentEntity implements java.io.Serializable {
private String id;
@Excel(name = "学生姓名", height = 20, width = 30, isimportField = "true")
private String name;
@Excel(name = "学生性别", replace = {"男_1", "女_2"}, suffix = "生", isimportField = "true")
private int sex;
@Excel(name = "出生日期", exportFormat = "yyyyMMddHHmmss", format = "yyyy-MM-dd", isimportField = "true", width = 20)
private Date birthday;
}
TeacherEntity.java
@Data
public class TeacherEntity implements java.io.Serializable {
@Excel(name = "教师姓名", width = 30, orderNum = "1", isimportField = "true",needMerge = true)
private String name;
@Excel(name = "教师性别", replace = {"男_1", "女_2"}, suffix = "生", isimportField = "true", orderNum = "2",needMerge = true)
private int sex;
}
工具类
package com.hl.springbooteasypoi.util;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelimportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.importParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelimportResult;
import cn.afterturn.easypoi.excel.imports.ExcelimportService;
import cn.afterturn.easypoi.handler.inter.IExcelVerifyHandler;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
public class ExcelUtils {
public static void exportExcel(List> list, String title, String sheetName,
Class> pojoClass, String fileName,
boolean isCreateHeader, HttpServletResponse response) throws IOException {
ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
exportParams.setCreateHeadRows(isCreateHeader);
defaultExport(list, pojoClass, fileName, response, exportParams);
}
public static void exportExcel(List> list, String title, String sheetName, Class> pojoClass, String fileName, HttpServletResponse response) throws IOException {
defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.XSSF));
}
public static void exportExcel(List> list, Class> pojoClass, String fileName, ExportParams exportParams, HttpServletResponse response) throws IOException {
defaultExport(list, pojoClass, fileName, response, exportParams);
}
public static void exportExcel(List
service
@Service
public class ExportExcelService {
public HttpResponseTemp> exportExcel(HttpServletResponse response) throws IOException {
List courseEntityList = new ArrayList<>();
CourseEntity courseEntity = new CourseEntity();
courseEntity.setId("1");
courseEntity.setName("测试课程");
TeacherEntity teacherEntity = new TeacherEntity();
teacherEntity.setName("张老师");
teacherEntity.setSex(1);
courseEntity.setMathTeacher(teacherEntity);
List studentEntities = new ArrayList<>();
for (int i = 1; i <= 2; i++) {
StudentEntity studentEntity = new StudentEntity();
studentEntity.setName("学生" + i);
studentEntity.setSex(i);
studentEntity.setBirthday(new Date());
studentEntities.add(studentEntity);
}
courseEntity.setStudents(studentEntities);
courseEntityList.add(courseEntity);
Date start = new Date();
String fileName = "导出文件";
ExcelUtils.exportExcel(courseEntityList,"导出测试","测试",CourseEntity.class,fileName,true,response);
System.out.println(System.currentTimeMillis() - start.getTime());
return ResultStat.OK.wrap(null,"导出成功");
}
}
controller
@Controller
@RequestMapping("/user")
public class ExportExcelController {
@Autowired
private ExportExcelService exportExcelService;
@GetMapping("/export")
public HttpResponseTemp> exportExcel(HttpServletResponse response) throws IOException {
return exportExcelService.exportExcel(response);
}
}
导出结果
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5amdI3eO-1637580252521)(springboot:整合easypoi.assets/image-20211122152259679.png)]
二、导入 普通导入 controller 和service@Controller
@RequestMapping("/user")
public class importExcelController {
@Autowired
private importService importService;
@PostMapping("/import")
HttpResponseTemp> importExcel(MultipartFile file) throws Exception {
return importService.importExcel(file);
}
}
@Service
public class importService {
public HttpResponseTemp> importExcel(MultipartFile file) throws Exception {
List courseEntityList = ExcelUtils.importExcel(file,1,2,CourseEntity.class);
System.out.println("成功导入:" + JSONUtil.toJsonStr(courseEntityList));
return ResultStat.OK.wrap(courseEntityList,"导入成功");
}
}
导入结果
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kKcz7GrE-1637580252523)(springboot:整合easypoi.assets/image-20211122162005668.png)]
校验导入现在产品需要对导入的Excel进行校验,不合法的Excel不允许入库,需要返回具体的错误信息给前端,提示给用户,错误信息中需要包含行号以及对应的错误。
因为 EasyPOI 支持 Hibernate Validator ,所以直接使用就可以了,因为要将错误信息以及错误行号返回,所以需要用到 EasyPOI 的高级用法,实现 IExcelDataModel与 IExcelModel接口,IExcelDataModel负责设置行号,IExcelModel 负责设置错误信息
修改实体类实现 IExcelDataModel与 IExcelModel接口,并且重写其中的方法,并且自定义errorMsg和rowNum来接受下面重写接口的值
这里需要注意俩点:
1.如果要对这个字段进行校验需要 isimportField = "true"参数
2.如果想要嵌套校验,需要在被嵌套的对象上加入@Valid注解
@Data
@ExcelTarget("courseEntity")
public class CourseEntity implements Serializable,IExcelModel,IExcelDataModel {
private String id;
@Excel(name = "课程名称", orderNum = "0", width = 25, needMerge = true,isimportField = "true")
@NotBlank(message = "课程名称不能为空")
private String name;
@Valid
@ExcelEntity(id = "absent")
private TeacherEntity mathTeacher;
@Valid
@ExcelCollection(name = "学生", orderNum = "2")
private List students;
private String errorMsg; //自定义一个errorMsg接受下面重写IExcelModel接口的get和setErrorMsg方法。
private Integer rowNum; //自定义一个rowNum接受下面重写IExcelModel接口的get和setRowNum方法。
@Override
public String getErrorMsg() {
return errorMsg;
}
@Override
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
@Override
public int getRowNum() {
return rowNum;
}
@Override
public void setRowNum(int rowNum) {
this.rowNum = rowNum;
}
}
@Data
public class StudentEntity implements java.io.Serializable {
private String id;
@Excel(name = "学生姓名",width = 30, isimportField = "true")
@NotBlank(message = "学生姓名不可以为空")
private String name;
@Excel(name = "学生性别", replace = {"男_1", "女_2"}, suffix = "生", isimportField = "true")
private int sex;
@Excel(name = "出生日期", exportFormat = "yyyy-MM-dd", format = "yyyy-MM-dd", isimportField = "true", width = 20)
private Date birthday;
}
@Data
public class TeacherEntity implements java.io.Serializable {
@Excel(name = "教师姓名", width = 30, orderNum = "1", isimportField = "true",needMerge = true)
@NotBlank(message = "教师姓名不可以为空")
private String name;
@Excel(name = "教师性别", replace = {"男_1", "女_2"}, suffix = "生", isimportField = "true", orderNum = "2",needMerge = true)
@NotNull(message = "教师性别不可以为空")
private int sex;
}
自定义校验类
package com.hl.springbooteasypoi.verifyHandler; import cn.afterturn.easypoi.excel.entity.result.ExcelVerifyHandlerResult; import cn.afterturn.easypoi.handler.inter.IExcelVerifyHandler; import com.hl.springbooteasypoi.pojo.CourseEntity; public class MyVerifyHandler implements IExcelVerifyHandlercontroller和service{ @Override public ExcelVerifyHandlerResult verifyHandler(CourseEntity courseEntity) { ExcelVerifyHandlerResult result = new ExcelVerifyHandlerResult(); //假设我们要添加用户, //现在去数据库查询getName,如果存在则表示校验不通过。 //假设现在数据库中有个getName 测试课程 if ("测试课程".equals(courseEntity.getName())) { result.setMsg("该课程已存在"); result.setSuccess(false); return result; } result.setSuccess(true); return result; } }
public HttpResponseTemp> checkimportExcel(MultipartFile file) throws IOException {
ExcelimportResult excelimportResult = ExcelUtils.importExcelResult(file, 1, 2, true, new MyVerifyHandler(), CourseEntity.class);
//成功导入
List list = excelimportResult.getList();
//失败导入
List failList = excelimportResult.getFailList();
HashSet set = new HashSet<>();
for (CourseEntity courseEntity : failList) {
int rowNum = courseEntity.getRowNum();
String errorMsg = courseEntity.getErrorMsg();
String msg = "第" + rowNum + "行的错误是:" + errorMsg;
set.add(msg);
}
System.out.println("导入成功:" + JSONUtil.toJsonStr(list));
System.out.println("导入失败:" + JSONUtil.toJsonStr(failList));
System.out.println("错误信息:" + JSONUtil.toJsonStr(set));
return ResultStat.OK.wrap(null,"导入成功");
}
@Controller
@RequestMapping("/user")
public class importExcelController {
@Autowired
private importService importService;
@PostMapping("/checkimport")
HttpResponseTemp> checkimportExcel(MultipartFile file) throws Exception {
return importService.checkimportExcel(file);
}
}
校验结果
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5KtmdsaM-1637580252524)(springboot:整合easypoi.assets/image-20211122192307115.png)]



