一、简介
在项目中,经常会有导出报表的需求,使用apache的POI自己需要写大量复杂的操作,因此使用easypoi来导出更为便捷
easypoi功能如同名字easy,主打的功能就是容易,让一个没见接触过poi的人员 就可以方便的写出Excel导出,Excel模板导出,Excel导入,Word模板导出,通过简单的注解和模板 语言(熟悉的表达式语法),完成以前复杂的写法
步骤:
1、引入依赖
2、创建javaBean并添加注解
3、添加数据,使用Easypoi工具类生成Workbook对象,存储为文件(导出)
二、引入依赖
<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>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
三、创建javaBean并添加注解
package com.xiaomin;
import cn.afterturn.easypoi.excel.annotation.Excel;
/**
* @author 晓敏
* @create 2019-11-11 11:24
*/
public class Student {
@Excel(name = "序号")
private int id;
@Excel(name = "姓名")
private String name;
@Excel(name = "年龄")
private int age;
@Excel(name = "性别")
private String sex;
public Student(int id, String name, int age, String sex) {
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
四、添加数据,使用Easypoi工具类生成Workbook对象,存储为文件(导出)
创建一个测试类
package com.xiaomin;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.FileOutputStream;
import java.util.ArrayList;
/**
* @author 晓敏
* @create 2019-11-11 11:28
*/
public class TestExcel {
public static void main(String[] args)throws Exception {
Student s1 = new Student(1,"张三",21,"男");
Student s2 = new Student(2,"李四",25,"女");
Student s3 = new Student(3,"王五",22,"男");
Student s4 = new Student(4,"赵六",24,"女");
Student s5 = new Student(5,"钱孙",26,"男");
Student s6 = new Student(6,"张九",18,"女");
ArrayList list = new ArrayList();
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
list.add(s6);
Workbook wb = ExcelExportUtil.exportExcel(new ExportParams("一班学生", "学生"), Student.class, list);
//保存数据
FileOutputStream outputStream = new FileOutputStream("D:\\student.xls");
wb.write(outputStream);
outputStream.close();
}
}