EasyPOI的基本使用

x33g5p2x  于2021-09-29 转载在 其他  
字(7.0k)|赞(0)|评价(0)|浏览(849)

引入依赖

SSM 项目,引入依赖

如果spring的版本是4.x的话引入的easypoi的版本是3.0.1,如果spring是5.x的话引入easypoi的版本是4.0.0

  1. <dependency>
  2. <groupId>cn.afterturn</groupId>
  3. <artifactId>easypoi-base</artifactId>
  4. <version>4.0.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>cn.afterturn</groupId>
  8. <artifactId>easypoi-web</artifactId>
  9. <version>4.0.0</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>cn.afterturn</groupId>
  13. <artifactId>easypoi-annotation</artifactId>
  14. <version>4.0.0</version>
  15. </dependency>

Spring Boot 项目(2.x以上的版本,我demo的版本是2.1.3.RELEASE),引入依赖

  1. <dependency>
  2. <groupId>cn.afterturn</groupId>
  3. <artifactId>easypoi-spring-boot-starter</artifactId>
  4. <version>4.0.0</version>
  5. </dependency>

需要注意的是由于easypoi的依赖内部依赖原生的poi,所以,引入了easypoi的依赖之后,需要把原生的poi的依赖删掉

注解方式导出Excel

导出测试的demo
  1. @Test
  2. public void testExportExcel() throws Exception {
  3. List<CourseEntity> courseEntityList = new ArrayList<>();
  4. CourseEntity courseEntity = new CourseEntity();
  5. courseEntity.setId("1");
  6. courseEntity.setName("测试课程");
  7. TeacherEntity teacherEntity = new TeacherEntity();
  8. teacherEntity.setName("张老师");
  9. teacherEntity.setSex(1);
  10. courseEntity.setMathTeacher(teacherEntity);
  11. List<StudentEntity> studentEntities = new ArrayList<>();
  12. for (int i = 1; i <= 2; i++) {
  13. StudentEntity studentEntity = new StudentEntity();
  14. studentEntity.setName("学生" + i);
  15. studentEntity.setSex(i);
  16. studentEntity.setBirthday(new Date());
  17. studentEntities.add(studentEntity);
  18. }
  19. courseEntity.setStudents(studentEntities);
  20. courseEntityList.add(courseEntity);
  21. System.out.println(courseEntityList+"11111111111111");
  22. Date start = new Date();
  23. Workbook workbook = ExcelExportUtil.exportExcel( new ExportParams("导出测试",
  24. null, "测试"),
  25. CourseEntity.class, courseEntityList);
  26. System.out.println(new Date().getTime() - start.getTime());
  27. File savefile = new File("E:/desktop/excel/");
  28. if (!savefile.exists()) {
  29. savefile.mkdirs();
  30. }
  31. FileOutputStream fos = new FileOutputStream("E:/desktop/excel/教师课程学生导出测试.xls");
  32. workbook.write(fos);
  33. fos.close();
  34. }
导出对应的Bean

CourseEntity 类。

  1. package com.mye.hl11easypoi.api.pojo;
  2. import cn.afterturn.easypoi.excel.annotation.Excel;
  3. import cn.afterturn.easypoi.excel.annotation.ExcelCollection;
  4. import cn.afterturn.easypoi.excel.annotation.ExcelEntity;
  5. import cn.afterturn.easypoi.excel.annotation.ExcelTarget;
  6. import lombok.Data;
  7. import java.util.List;
  8. @Data
  9. @ExcelTarget("courseEntity")
  10. public class CourseEntity implements java.io.Serializable {
  11. /** * 主键 */
  12. private String id;
  13. /** * 课程名称 * needMerge 是否需要纵向合并单元格(用于list创建的多个row) */
  14. @Excel(name = "课程名称", orderNum = "0", width = 25, needMerge = true)
  15. private String name;
  16. /** * 老师主键 */
  17. // @ExcelEntity(id = "major")
  18. private TeacherEntity chineseTeacher;
  19. /** * 老师主键 */
  20. @ExcelEntity(id = "absent")
  21. private TeacherEntity mathTeacher;
  22. @ExcelCollection(name = "学生", orderNum = "3")
  23. private List<StudentEntity> students;
  24. }

TeacherEntity 类

  1. package com.mye.hl11easypoi.api.pojo;
  2. import cn.afterturn.easypoi.excel.annotation.Excel;
  3. import lombok.Data;
  4. @Data
  5. public class TeacherEntity {
  6. /** * 教师名称 * isImportField 导入Excel时,对Excel中的字段进行校验,如果没有该字段,导入失败 */
  7. @Excel(name = "教师姓名", width = 30, orderNum = "1" ,isImportField = "true")
  8. private String name;
  9. /** * 教师性别 * replace 值的替换,`replace = {"男_1", "女_2"} `将值为1的替换为男 * suffix 文字后缀 */
  10. @Excel(name = "教师性别", replace = {"男_1", "女_2"}, suffix = "生", isImportField = "true_st",orderNum = "2")
  11. private int sex;
  12. }

StudentEntity 类

  1. package com.mye.hl11easypoi.api.pojo;
  2. import cn.afterturn.easypoi.excel.annotation.Excel;
  3. import lombok.Data;
  4. import java.util.Date;
  5. @Data
  6. public class StudentEntity implements java.io.Serializable {
  7. /** * id */
  8. private String id;
  9. /** * 学生姓名 */
  10. @Excel(name = "学生姓名", height = 20, width = 30, isImportField = "true_st")
  11. private String name;
  12. /** * 学生性别 */
  13. @Excel(name = "学生性别", replace = {"男_1", "女_2"}, suffix = "生", isImportField = "true_st")
  14. private int sex;
  15. @Excel(name = "出生日期", exportFormat = "yyyyMMddHHmmss", format = "yyyy-MM-dd", isImportField = "true_st", width = 20)
  16. private Date birthday;
  17. @Excel(name = "进校日期", exportFormat = "yyyyMMddHHmmss", format = "yyyy-MM-dd")
  18. private Date registrationDate;
  19. }
导出结果

注解方式导入Excel

ImportParams参数
属性类型默认值功能
titleRowsint0表格标题行数
headRowsint1表头行数
startRowsint0字段值与列标题之间的距离
keyIndexint0主键
startSheetIndexint0开始读取的sheet位置
sheetNumint1上传表格需要读取的sheet数量
needSavebooleanfalse是否需要保存上传的Excel
needVerfiybooleanfalse是否需要校验上传的Excel
verifyHanlderIExcelVerifyHandlernull校验处理接口自定义校验
importFieldsString[]null导入时校验数据模板,是不是正确的Excel
saveUrlString“upload/excelUpload”保存上传的Excel目录,默认是如TestEntity这个类保存路径是upload/excelUpload/Test/yyyyMMddHHmmss

需要说明的是
1、titleRows表示的是表格标题行数,如果没有就是0,如果有一个标题就是1,如果是两个标题就2

2. headRows表示的是表头行数,默认是1,如果有两个表头则需要设置2

导入代码

  1. @Test
  2. public void testImport2() throws Exception {
  3. // 参数1:导入excel文件流 参数2:导入类型 参数3:导入的配置对象
  4. ImportParams importParams = new ImportParams();
  5. importParams.setTitleRows(1); // 设置标题列占几行
  6. importParams.setHeadRows(2); // 设置字段名称占几行 即header
  7. importParams.setNeedVerify(true);//开启校验
  8. importParams.setStartSheetIndex(0); // 设置从第几张表格开始读取,这里0代表第一张表,默认从第一张表读取
  9. List<CourseEntity> courseEntityList = ExcelImportUtil.importExcel(new FileInputStream("E:/desktop/excel/教师课程学生导出测试.xls"), CourseEntity.class, importParams);
  10. for (CourseEntity courseEntity : courseEntityList) {
  11. System.out.println(courseEntity);
  12. }
  13. }

导入结果

  1. CourseEntity(
  2. id=null,
  3. name=测试课程,
  4. chineseTeacher=null,
  5. mathTeacher=TeacherEntity(name=张老师, sex=1),
  6. students=[StudentEntity(
  7. id=null,
  8. name=学生1,
  9. sex=1,
  10. birthday=Wed Aug 03 20:31:23 CST 5881510, registrationDate=null),
  11. StudentEntity(
  12. id=null,
  13. name=学生2,
  14. sex=2,
  15. birthday=Wed Aug 03 20:31:23 CST 5881510, registrationDate=null)]
  16. )

Excel导入校验

EasyPoi的校验使用也很简单,在导入对象上加上通用的校验规则或者这定义的这个看你用的哪个实现然后params.setNeedVerfiy(true);配置下需要校验就可以了

  1. /** * Email校验 */
  2. @Excel(name = "Email", width = 25)
  3. private String email;
  4. /** * 最大 */
  5. @Excel(name = "Max")
  6. @Max(value = 15,message = "max 最大值不能超过15" ,groups = {ViliGroupOne.class})
  7. private int max;
  8. /** * 最小 */
  9. @Excel(name = "Min")
  10. @Min(value = 3, groups = {ViliGroupTwo.class})
  11. private int min;
  12. /** * 非空校验 */
  13. @Excel(name = "NotNull")
  14. @NotNull
  15. private String notNull;
  16. /** * 正则校验 */
  17. @Excel(name = "Regex")
  18. @Pattern(regexp = "[\u4E00-\u9FA5]*", message = "不是中文")
  19. private String regex;

使用方式就是在导入时设置needVerfiy属性为true。

  1. @Test
  2. public void basetest() {
  3. try {
  4. ImportParams params = new ImportParams();
  5. params.setNeedVerfiy(true);
  6. params.setVerfiyGroup(new Class[]{ViliGroupOne.class});
  7. ExcelImportResult<ExcelVerifyEntity> result = ExcelImportUtil.importExcelMore(
  8. new File(PoiPublicUtil.getWebRootPath("import/verfiy.xlsx")),
  9. ExcelVerifyEntity.class, params);
  10. FileOutputStream fos = new FileOutputStream("D:/excel/ExcelVerifyTest.basetest.xlsx");
  11. result.getWorkbook().write(fos);
  12. fos.close();
  13. for (int i = 0; i < result.getList().size(); i++) {
  14. System.out.println(ReflectionToStringBuilder.toString(result.getList().get(i)));
  15. }
  16. Assert.assertTrue(result.getList().size() == 1);
  17. Assert.assertTrue(result.isVerfiyFail());
  18. } catch (Exception e) {
  19. LOGGER.error(e.getMessage(),e);

相关文章