第一步
maven依赖引入
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
第二步
创建写对象
@Data
public class ExcelData {
String erp;
String deptCpde;
String info;
}
第三步
构造数据,实际使用的时候,替换成对应查库或者接口
private List<ExcelData> data() {
List<ExcelData> list = Lists.newArrayList();
for (int i = 0; i < 10; i++) {
ExcelData data = new ExcelData();
data.setErp("erp" + i);
data.setDeptCpde("dept"+i);
data.setInfo("info"+i);
list.add(data);
}
return list;
}
第四步
调用
private static void writeExcel(String path){
//本地测试或者worker应用,获取的是当前模块的classess下
// String path = new TeamInfoService().getClass().getClassLoader().getResource("/").getPath();
//web项目,获取tomcat运行根路径,request通过controller传过来,controller的request 来之于@Autowired
// protected HttpServletRequest request;
String path = request.getSession().getServletContext().getRealPath("/");
String fileName = path + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
EasyExcel.write(fileName, ExcelData.class)
.sheet("模板")
.doWrite(() -> {
// 分页查询数据
return data();
});
}