JAVA使用Chimm.Excel通过“设置模板,填充数据”实现excel下载

前言

感谢 吃茫茫 大佬分享的开源项目 Chimm.Excel ,以下是个人的使用心得。内容大多来自于作者,详情下载项目源码查看即可。
这里只给出了最基本的数据填充并下载功能,其他功能请看 Chimm.Excel 的 README.md 或项目源码。 Chimm.Excel 依赖于poi, Chimm.Excel 未提供的功能可以通过poi手动实现。

1. 项目介绍(搬运)

1.1 简介

Chimm.Excel 是什么? 该程序是一个用 Java 写的 Excel 生成工具,基于模板操作,简单,快捷,易上手。

1.2 特性

数据组装方式大有不同

和网上部分开源软件的区别是,这个程序是基于 excel 模板驱动的,需要在模版里填写变量名称,而并非在程序中添加注解。

为什么不采用基于注解的方式?

网上一些基于注解的 excel 导出,基本上只能导出简单的表格样式。该程序使用的是 excel 模板,所以可以导出一些比较复杂的表格样式。

Antlr4

Antlr (ANother Tool for Language Recognition) 是一个强大的跨语言语法解析器,可以用来读取、处理、执行或翻译结构化文本或二进制文件。它被广泛用来构建语言,工具和框架。Antlr可以从语法上来生成一个可以构建和遍历解析树的解析器。由于该程序是基于 Antlr4 进行开发的,所以在变量定义上面,非常的灵活,我们可以定义集合变量,甚至我们还可以在公式中定义变量。一个表格对应一个数据对象,开发人员只需查询数据、组装数据即可。

excel 模板如何生成?

模板生成非常的简单,我们定义变量的时候,只需要使用 $ + 大小括号 包围的形式即可,如:${school.name}。

Chimm.Excel 功能简介

  • 导出excel二进制文件
  • 根据模板中的变量,将值写入
  • 支持公式
  • 支持带变量的公式,如:SUM(A1,A2,${demo.value})
  • 操作表格添加/减少行
  • ⭐️添加行会自动更新公式
  • 合并单元格(支持批量合并)
  • 更改单元格边框样式(加粗、虚线等)
  • 支持设置超链接(v1.2.0)

2. 功能展示

execl模板(测试表格.xlsx)如下:
模板execl
导出execl结果如下:
结果execl

3. 项目结构

项目使用springboot快速搭建,如有不合理的地方… …就让他不合理吧,不合理你就自己改改,你看得懂就行。🙃
项目结构
maven位置:

<!-- https://mvnrepository.com/artifact/com.github.chimmhuang/chimm.excel -->
<dependency>
    <groupId>com.github.chimmhuang</groupId>
    <artifactId>chimm.excel</artifactId>
    <version>1.3.0</version>
</dependency>

ExeclController:

@RestController
public class ExcelController {

    @GetMapping(value = "getChimmExcel")
    public ResponseEntity<byte[]> getChimmExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取文件的二进制
        File file = new File("src/main/resources/static/测试表格.xlsx");
        byte[] bytes = FileUtils.readFileToByteArray(file);
        // 通过 ExcelHelper 获取 excel 表格对象
        ExcelWorkbook excelWorkbook = ExcelHelper.createWorkbook(bytes);

        // 获取指定的 sheet 页(该对象即是我们设置好的表格模板)
        SheetTable table = excelWorkbook.getSheet(0);
        // 设置 自定义 sheet 页名称
        table.setSheetName("成绩表");

        // 获取封装的对象
        ClassRoom classRoom = ClassRoom.getClassRoomDemo();

        Row copy = table.getRow(3);
        // 将 rowNum 大于 13 的都删除,进行动态表格添加
        table.removeRowGE(3);
        for (int i = 0; i < classRoom.getStudents().size(); i++) {
            // 此处直接设置值也行。设置值或者设置变量,建议统一。我在此处设置为变量
            copy.getCell("A").setValue("${students[" + i + "].name}");
            copy.getCell("B").setValue("${students[" + i + "].sex}");
            copy.getCell("C").setValue("${students[" + i + "].age}");
            copy.getCell("D").setValue("${students[" + i + "].score}");
//            copy.getCell("A").setValue(classRoom.getStudents().get(i).getName());
//            copy.getCell("B").setValue(classRoom.getStudents().get(i).getSex());
//            copy.getCell("C").setValue(classRoom.getStudents().get(i).getAge());
//            copy.getCell("D").setValue(classRoom.getStudents().get(i).getScore());
            // 设置完毕后,添加进表格
            table.appendRow(copy);
        }
        
		// 作者还提供了合并单元格、公式、更改样式等功能,这里不展示,需要的话下载 Chimm.Excel 源码看看吧

        // 将封装好的表格对象,填充到 excel 表格中
        ExcelHelper.fillInData(table, classRoom);

        // 将表格对象转换为二进制,resultBytes 即是最终想要的结果
        byte[] resultBytes = ExcelHelper.convert2Byte(table);

        // 设置http返回头
        HttpHeaders headers = new HttpHeaders();
        headers.add("contentType", "application/octet-stream");
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", LocalDate.now().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));

        return new ResponseEntity<>(resultBytes, headers, HttpStatus.CREATED);
    }
}

ClassRoom:

@Data
public class ClassRoom {
    private String className;

    private List<Student> students;

    public static ClassRoom getClassRoomDemo() {
        ClassRoom classRoom = new ClassRoom();
        List<Student> students = new ArrayList<>();
        classRoom.setClassName("华师大软件学院B班");
        for (int i = 0; i < 5; i++) {
            Student student = new Student();
            student.setName("学生" + i);
            student.setSex("男");
            student.setAge(23 + i);
            student.setScore(80 + i);
            students.add(student);
        }
        classRoom.setStudents(students);
        return classRoom;
    }
}

Student:

@Data
public class Student {
    private String name;
    private String sex;
    private Integer age;
    private Integer score;
}

3. 小结

对表格样式有要求的情况下,使用 Chimm.Excel 可以节省大量的通过调整表格样式的时间(因为模板中样式已经设定好),大大的提高了实现导出excel功能的效率。

但是,如果表格中插入动态的集合列表数据的操作还是略显麻烦,需要写循环插入。如果后面能实现只要一个${xxx}就能完成列表插入的话会更加方便。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值