EasyPoi,
主打简单,不过
功用依然OK(绝对够用)。
入门实例
基于maven项目
1.导包
<!-- 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>
2.实体类
@ExcelTarget("emp")
public class POIEmployee {
/**
@Excel:代表这个字段要生成到excel中去
*/
private Long id;
//name:这个excel的表头名称
@Excel(name = "用户名")
private String username;
//width:格子的宽度
@Excel(name = "邮箱",width=20)
private String email;
@Excel(name = "年龄")
private Integer age;
//replace:替换 true就会显示男,false显示女
@Excel(name = "性别", replace = { "男_true", "女_false" })
private Boolean sex;
//format:导入和导出的日期格式 注:如果数据库是varchar,还需要配置databaseFormat
@Excel(name = "出生日期",width = 20,format="yyyy-MM-dd HH:mm:ss")
private Date bornDate = new Date();
//type=2代表它是一张图片
@Excel(name = "头像",type = 2 ,width = 20 , height = 20)
private String headImage;
@ExcelEntity
private POIDepartment department;
...
}
public class Department {
private Long id;
@Excel(name = "部门名称_emp") //@ExcelEntity(id="emp"):对应另一个关连对象
private String name;
}
3.测试代码
导出
public class EasyPOITest {
//导出
@Test
public void test() throws Exception{
POIDepartment d1 = new POIDepartment();
d1.setId(1L);
d1.setName("俱乐部");
POIEmployee e1 = new POIEmployee();
e1.setId(1L);
e1.setUsername("小王");
e1.setEmail("wang@qq.com");
e1.setAge(12);
e1.setSex(true);
e1.setHeadImage("images/1.png");
e1.setDepartment(d1);
POIEmployee e2 = new POIEmployee();
e2.setId(2L);
e2.setUsername("小李");
e2.setEmail("li@qq.com");
e2.setAge(18);
e2.setSex(false);
e2.setHeadImage("images/3.png");
e2.setDepartment(d1);
//准备数据(以后是直接读取这些数据)
List<POIEmployee> list = new ArrayList<>();
list.add(e1);
list.add(e2);
/**
* 参数一:导出的一些属性
* title:标题 sheetName:表名
* 参数二:导出的数据类型
* 参数三:导出的数据
*/
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("员工信息","员工数据"),POIEmployee.class, list);
保存数据,输出
FileOutputStream out = new FileOutputStream("emphaha.xlsx");
workbook.write(out);
out.close();
}
}
导入
@Test
public void test2() {
ImportParams params = new ImportParams();
params.setTitleRows(1);
params.setHeadRows(1);
List<PoiUser> list = ExcelImportUtil.importExcel(new File("员工.xlsx"), PoiUser.class, params);
}