为什么使用jxls ?
在项目开发中,涉及到了复杂excel的导出(数据输出不规则,且遍历list数据时数据不在同一行,还有图片的输出到excel)。 一开始使用的是easypoi ,easypoi 有模板导出,但是奇葩的是在遍历list时,换行支持的不怎么好,经过一系列实战后,最后还是放弃了,然后试了试easyexcel ,功能也没达到预期,最后选择了jxls2
jxls2使用批注形式写表达式
jxls语法
${name} //普通插入
jx:area(lastCell="A2") //定义语法作用域
jx:image(lastCell="D11" src="treamBytes" imageType="PNG") //插入图片
jx:each(items="list" var="item" lastCell="F12") //遍历list
简单使用
程序
public static void main(String[] args) throws IOException {
OutputStream out = new FileOutputStream("E:\\temp\\demo\\out.xlsx");
InputStream in = new FileInputStream("E:\\temp\\demo\\template.xlsx");
List<Map<String, Object>> list = new ArrayList<>();
byte[] imgBytes = IOUtils.toByteArray(new FileInputStream("E:\\img\\123.png"));
for (int i = 0; i < 3; i++) {
Map<String, Object> map = new HashMap<>();
map.put("name", "palmer" + i);
map.put("age", 18 + i);
map.put("address", "地址" + i);
list.add(map);
}
Context context = new Context();
context.putVar("name", "palmer");
context.putVar("list", list);
context.putVar("imgBytes", imgBytes);
JxlsHelper.getInstance().processTemplate(in, out, context);
out.close();
in.close();
}
模板
结果