运行环境: jdk1.8 idea SpringBoot
利用Maven管理Jar包
在pom 文件中导入easypoi的jar包
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.0.3</version>
</dependency>
其他需要的jar如(SpringBoot测试类的jar)请自行引入 ,如果用Idea 创建项目他会自己帮你引入你这个项目需要的jar包
,
创建包com.ruanjian.dao 在包下面创建Bean类
如
package com.ruanjian.dao; import cn.afterturn.easypoi.excel.annotation.Excel; import java.io.Serializable; import java.util.Date; /** * @autohr 任浩, * @create 2019-01-13-21:02 */ public class People implements Serializable { /*orderNum 是在excel 表格中的列 replace 1代表男 2代表女 */ @Excel(name = "学生id" ,orderNum = "0") private Integer id; @Excel(name = "学生姓名",orderNum ="1" ) private String name; @Excel(name = "学生年龄" ,orderNum = "2") private int age; @Excel(name = "性别",replace = {"男_1", "女_2"}) private int sex; public People(Integer id, String name, int age, int sex, Date date) { this.id = id; this.name = name; this.age = age; this.sex = sex; this.date = date; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } @Excel(name = "入学时间",exportFormat ="yyyy-MM-dd") private Date date; public People() { } public Integer getId() { return id; } public void setId(Integer 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 int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public People(Integer id, String name, int age, int sex) { this.id = id; this.name = name; this.age = age; this.sex = sex; } }
在测试类中编写代码
1.实例化这个Bean(用来模拟数据库的数据)
People people = new People();
people.setAge(12);
people.setId(1);
people.setSex(1);
people.setName("张三");
2.将值放入到List集合中
ArrayList<People> peopleList = new ArrayList<>();
peopleList.add(people);
3.调用方法 (这个变量sheets 就相当于一个excel 的表格)
Workbook sheets = ExcelExportUtil.exportExcel(new ExportParams("物联一班", "测试"), People.class, peopleList);
得到的结果数据样式
4.设置写出的地址
String fileName = "D:\\test.xls";
5.开始写入
try {
FileOutputStream outputStream = new FileOutputStream(fileName);
sheets.write(outputStream);
System.out.println("写入成功");
} catch (Exception e) {
e.printStackTrace();
}
FileOutPutStream 的参数(fileName)为刚才设置的要写入磁盘的地址
6.大功告成......
参考文档: http://easypoi.mydoc.io/