Easypoi导入介绍
导入演示
需要导入的excel
添加依赖
<!--easypoi相关依赖-->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.2.0</version>
</dependency>
实体类
@Data
@ExcelTarget("emp") //注意 name = "编号" ,值一定要和excel表中列名一致,顺序不要求
public class Emp implements Serializable {
@Excel(name = "编号")
private String id;
@Excel(name = "姓名")
private String name;
@Excel(name = "生日", format ="yy年MM月dd日 HH时mm分ss秒")
private Date bir;
@Excel(name = "年龄") //注意此处年龄为Integer类型,例:20岁,导入时会报错,注意类型
private Integer age;
@Excel(name = "状态", replace = {"启用_1", "未启用_0"})
private String state;
}
导入测试
/**
* Easypoi导入测试
*/
public class ImportTest {
@Test
public void importTest() throws Exception {
//参数1:文件的输入流,参数2:文件导入对应的实体类字节码,参数3:params参数设置
ImportParams params = new ImportParams();
params.setTitleRows(1); //设置标题占几列 (例:信息表)
params.setHeadRows(2); //设置header列占几列, (例:编号 姓名 ...)
//params.setStartSheetIndex(1); //表示读取上传的第二个sheet, 第一个sheet默认为0
//params.setSheetNum(3); //有startSheet表示从start到3(如数据大分表方便看,注意字段名一致),如果没有startSheet表示从0到3
params.setImportFields(new String[]{"编号","年龄"}); //列名检查,如果有 编号 年龄 才是合法的,没有的话就不合法
List<Emp> list = ExcelImportUtil.importExcel(new FileInputStream("F:\\easypoiTest\\importTest.xlsx"), Emp.class, params);
list.forEach(System.out::println);
}
}
可能的问题:
excel导入时,Date类型的数据,读取可能为null
解决:
使用 importFormat 和 exportFormat 设置导入导出的时间格式,这样就能获取到数据,最好都设置
@ApiModelProperty(value = "创建时间")
@Excel(name = "创建时间", width = 20.0, importFormat = "yyyy-MM-dd HH:mm:ss", exportFormat = "yyyy-MM-dd HH:mm:ss")
private Date cjsj;