0、背景
JXLS是一个基于Java的开源库,专门用于处理Excel文件。它通过简单的Excel中的批注
,实现复杂的Excel报表生成和数据导出功能,支持公式、样式、合并单元格
等。JXLS的核心优势优势:简化代码、模板与逻辑分离、性能优化
优势:
- 模板驱动:通过预定义的Excel模板(含特定标记)动态填充数据,支持公式、样式、合并单元格等复杂操作。
- 表达式支持:使用Apache JEXL或OGNL表达式在模板中定义动态内容,JEXL语法。
- 轻量级:依赖较少,仅需POI和表达式引擎库即可运行。
跨版本兼容:支持.xls(HSSF)和.xlsx(XSSF)格式的Excel文件。
基本介绍:
- 使用批注的模式编写指令
- 需在 excel 的第一个单元格指定整个模板的范围
- 单元格中取值与 el 表达式类似使用 ${} 来访问传入的变量
- 指令中需要访问对象则不需要使用 ${} 直接访问即可,需用 “” 包裹
- 官方文档2.x版本
- Github
1、快速入门
首先,我们通过一个简单的demo快速了解JXLS的能力。整个demo项目路径如下图所示。
1.1 maven依赖。
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls-poi</artifactId>
<version>2.14.0</version>
</dependency>
1.2 数据
完成项目依赖导入后,准备一个生成数据的工具类:
@Data
public class Student {
private String name;
private Integer age;
}
@Data
public class DataGen01 {
public static List<Student> getRandomStudents() {
List<Student> students = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Student student = new Student();
student.setName("name" + i);
student.setAge(i);
students.add(student);
}
return students;
}
}
1.3 模板绘制
在resources/template
目录下新建一个.xls
的Excel文件,然后绘制如下图所示模板。JXLS的语法是通过在Eexcel中插入批注
的方式实现的,且批注必须是 jx:
开头。其中jx:area
表示当前sheet页的JXLS
引擎解析的作用范围,下图是标准在A1单元格,lastCell=C2
,因此,只要在单元格[A1, C2]这个矩形内的 jx:
命令都会被解析。
因此,在绘制Excel模板时候,一定要有这个 jx:area
注释!~
因此,在绘制Excel模板时候,一定要有这个 jx:area
注释!~
因此,在绘制Excel模板时候,一定要有这个 jx:area
注释!~
jx:each
是循环命令,在循环命令作用域内的单元格会循环(默认方向是向下,可以手动添加jx:each(items="students" var="s" lastCell="B2",direction="RIGHT")
,循环的次数便是items
对象的个数,其中每个变量被定义为var
,通过${}
可以拿到s中的属性,在上图中,[A2, B2]矩形会向下遍历,
1.4 模板渲染
@Slf4j
public class EachCommandTest01 {
public static void main(String[] args) {
// 构建数据
List<Student> students = DataGen01.getRandomStudents();
// 加载模板
try(InputStream is = EachCommandTest01.class.getResourceAsStream("/template/student01.xls")) {
Path outputPath = Paths.get("output");
if (!Files.exists(outputPath)) {
Files.createDirectories(outputPath); // 创建 output 目录
}
DateFormat dateInstance = new SimpleDateFormat("yyyyMMddHHmmss");
String format = dateInstance.format(new Date());
try (OutputStream os = Files.newOutputStream(outputPath.resolve("student01_output" + format +".xls"))) {
// 把数据加入 jxls的 上下文中
Context context = new Context();
context.putVar("students", students);
// 渲染模板
JxlsHelper.getInstance().processTemplate(is, os, context);
} catch (IOException e) {
log.error("Error writing to file", e);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
运行该maven方法,在启动时候,记得把更改main方法设置,将provided
返回的依赖勾选上,否则可能启动报错。
启动后,会发现项目中生成了一个输出的文件,达到下图效果说明渲染成功~
2、命令
命令主要有以下几个,具体可以看 官网链接
3、组合效果
模板
输出效果:包含动态行,动态列,动态单元格,动态样式颜色