1、导包
在pom.xml中加入依赖如下:
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls</artifactId>
<version>2.4.</version>
</dependency>
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls-poi</artifactId>
<version>1.0.</version>
</dependency>
2、创建导出Excel的模板,实例如下:图1中的表达式(jx:each(items="object",var="order",lastCell="E4")),此处的object要与JxlsExporter.java中返回的集合的“键”保持一,下面给出可处理父子级关系的批注展示,类似于jstl中的each
图1 父级数据
图2 子级数据
图3 头部批注
说明:通过批注的形式,指定“作用域”范围,上图中lastCell表示在该坐标内输入表达式有效。
3、获取列表数据,并导出Excel,JxlsExporter.java 代码如下
package com.inmansoft.base.util; //template模板路径 import com.inmansoft.base.model.plan.LsBaseOrder;
import com.inmansoft.base.model.plan.LsDeptOrder;
import lombok.extern.slf4j.Slf4j;
import org.jxls.common.Context;
import org.jxls.transform.poi.PoiContext;
import org.jxls.util.JxlsHelper; import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random; /**
* <p>title:</p>
* <p>description:</p>
*
* @author: zsj
* @date Created in 2019-01-06
* @modified By zsj
*/
@Slf4j
public class JxlsExporter {
private static String template = "leadshow.xls";
private static String output = "target/export_leadshow.xls"; public static void main(String[] args) throws IOException {
log.info("导出数据");
execute();
} public static void execute() throws IOException {
List<LsBaseOrder> lsBaseOrders = createLsBaseOrders(6);
log.info("Opening input stream");
//template 为模板路径:eg:leadshow.xls,
// JxlsExporter.class.getResourceAsStream(template)—> leadshow.xls模板路径需放置在该类包路径下
try (InputStream is = JxlsExporter.class.getResourceAsStream(template)) {
//output 为导出的Excel路径,有一个坑需要注意的是,在springboot项目打包成jar包之后,
//导出文件路径可这样表示: System.getProperty("user.dir") + "/export_leadshow.xls",这种"static/export_leadshow.xls"路径会失效
try (OutputStream os = new FileOutputStream(output)) {
Context context = new PoiContext();
context.putVar("object", lsBaseOrders);
JxlsHelper.getInstance().processTemplate(is, os, context);
}
}
} public static List<LsBaseOrder> createLsBaseOrders(int num) {
List<LsBaseOrder> lsBaseOrders = new ArrayList<>();
Random random = new Random();
for (int i = 1; i <= num; i++) {
LsBaseOrder item = new LsBaseOrder();
item.setItemName("2835 LED硬灯条" + i);
item.setItemSpec("60珠 8500K");
item.setSimpleCode("简码-" + i);
item.setCompanyName("华为公司"); List<LsDeptOrder> lsDeptOrders = new ArrayList<>();
item.setChildren(lsDeptOrders);
for (int j = 1; j <= random.nextInt(10); j++) {
LsDeptOrder deptOrder1 = new LsDeptOrder();
deptOrder1.setItemName("变压器" + j);
deptOrder1.setFullNum(12);
lsDeptOrders.add(deptOrder1);
}
lsBaseOrders.add(item);
}
return lsBaseOrders;
}
}
模板路径如下:(与上面Java类包路径一致)