一、簡介
在項目中,經常會有導出報表的需求,使用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();
}
}