Java中使用poi+poi-tl实现根据模板导出word文档

场景

若依管理系统前后端分离版基于ElementUI和SpringBoot怎样实现Excel导入和导出:

若依管理系统前后端分离版基于ElementUI和SpringBoot怎样实现Excel导入和导出_若依导出前端获得到后端的execl流之后怎么操作-CSDN博客

上面讲的是Excel的导出,如果是需要根据word文档的模板,比如根据数据库中数据或者其它数据源循环

根据模板填充数据,可填充文字、图片、表格、图表等数据。

poi-tl

poi-tl(poi template language)是Word模板引擎,使用Word模板和数据创建很棒的Word文档。

poi-tl是一款采用Apache License 2.0开源协议的开源产品

poi-tl的github地址:

GitHub - Sayi/poi-tl: Generate awesome word(docx) with template

poi-tl技术文档地址:

Poi-tl Documentation

为什么使用poi-tl

poi-tl模板引擎功能

Word模板引擎功能描述

 文本

将标签渲染为文本

 图片

将标签渲染为图片

 表格

将标签渲染为表格

 列表

将标签渲染为列表

 图表

条形图(3D条形图)、柱形图(3D柱形图)、面积图(3D面积图)、折线图(3D折线图)、雷达图、饼图(3D饼图)、散点图等图表渲染

 If Condition判断

根据条件隐藏或者显示某些文档内容(包括文本、段落、图片、表格、列表、图表等)

 Foreach Loop循环

根据集合循环某些文档内容(包括文本、段落、图片、表格、列表、图表等)

 Loop表格行

循环复制渲染表格的某一行

 Loop表格列

循环复制渲染表格的某一列

 Loop有序列表

支持有序列表的循环,同时支持多级列表

 Highlight代码高亮

word中代码块高亮展示,支持26种语言和上百种着色样式

 Markdown

将Markdown渲染为word文档

 Word批注

完整的批注功能,创建批注、修改批注等

 Word附件

Word中插入附件

 SDT内容控件

内容控件内标签支持

 Textbox文本框

文本框内标签支持

 图片替换

将原有图片替换成另一张图片

 书签、锚点、超链接

支持设置书签,文档内锚点和超链接功能

 Expression Language

完全支持SpringEL表达式,可以扩展更多的表达式:OGNL, MVEL…​

 样式

模板即样式,同时代码也可以设置样式

 模板嵌套

模板包含子模板,子模板再包含子模板

 合并

Word合并Merge,也可以在指定位置进行合并

 用户自定义函数(插件)

插件化设计,在文档任何位置执行函数

注:

博客:
霸道流氓气质-CSDN博客

实现

1、快速开始

注意这里poi-tl与poi的对应关系

当前poi-tl的最新版本为1.12.2,需要对应poi的版本5.2.2+

如果poi不是用的该版本,则找对应版本的对应关系。

比如这里使用的poi版本为

            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml</artifactId>
                <version>4.1.2</version>
            </dependency>

则需要引入对应的poi-tl的版本为1.8.2

        <dependency>
            <groupId>com.deepoove</groupId>
            <artifactId>poi-tl</artifactId>
            <version>1.8.2</version>
        </dependency>

相应的文档地址

Poi-tl Documentation

2、新建模板文件,以docx后缀结尾

并在模板文件中需要显示内容的位置,添加标签

{{title}}

文本标签测试

新建渲染方法

    public static void render(Map<String, Object> map){
        XWPFTemplate template = XWPFTemplate.compile("D://test//temp.docx").render(map);
        try {
            FileOutputStream out = new FileOutputStream("D://test//output.docx");
            template.write(out);
            out.flush();
            out.close();
            template.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

其中temp.docx是模板文件,oupput.docx是输出的文件

调用渲染方法

        render(new HashMap<String, Object>(){{
            put("title", "Hi, poi-tl Word模板引擎");
        }});

运行结果

3、文本标签复杂属性

数据模型

String :文本

TextRenderData :有样式的文本

HyperLinkTextRenderData :超链接文本

Object :调用 toString() 方法转化为文本

示例代码

​
        HashMap<String, Object> data = new HashMap<>();
        data.put("name", "Sayi");
        data.put("start_time", "2019-08-04");
        data.put("author", new TextRenderData("000000", "Sayi"));
        data.put("author2", new TextRenderData("霸道的程序猿",
                StyleBuilder.newBuilder()
                        .buildColor("00FF00")//颜色
                        .buildStrike()//删除线
                        .buildBold()//粗体
                        .buildItalic()//斜体
                        .buildUnderLine()//下划线
                        .buildFontFamily("微软雅黑")//字体
                        .buildFontSize(12)//字号
                        .build()
        ));
        // 超链接
        data.put("link", new HyperLinkTextRenderData("website", "卅一"));
        // 锚点
        data.put("anchor", new HyperLinkTextRenderData("anchortxt", "anchor:appendix1"));
        render(data);

​

运行效果

4、图片标签

图片标签以@开始:{{@var}}

示例代码

​
        HashMap<String, Object> data = new HashMap<>();
        // 本地图片
        data.put("local", new PictureRenderData(80, 100, "D://test//test.png"));
        // 图片流
        try {
            data.put("localbyte", new PictureRenderData(80, 100, ".png", new FileInputStream("D://test//test.png")));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        // 网络图片(注意网络耗时对系统可能的性能影响)
        data.put("urlpicture", new PictureRenderData(50, 50, ".png", BytePictureUtils.getUrlBufferedImage("http://deepoove.com/images/icecream.png")));

        // java 图片
        try {
            BufferedImage image = ImageIO.read(new File("D://test//test.png"));
            data.put("bufferimage", new PictureRenderData(80, 100, ".png", image));
        } catch (IOException e) {
            e.printStackTrace();
        }
        render(data);

​

运行结果

5、表格标签

表格标签以#开始:{{#var}}

示例代码

        HashMap<String, Object> data = new HashMap<>();
        RowRenderData header = RowRenderData.build(new TextRenderData("000000", "姓名"), new TextRenderData("000000", "学历"));
        RowRenderData row0 = RowRenderData.build("张三", "研究生");
        RowRenderData row1 = RowRenderData.build("李四", "博士");
        data.put("table", new MiniTableRenderData(header, Arrays.asList(row0, row1)));
        render(data);

运行结果

6、图表标签-饼状图

模板文件中插入图表-饼状图

右击饼图,查看可选文字-输入

{{pieChart}}

编写测试代码

        HashMap<String, Object> data = new HashMap<>();
        ChartSingleSeriesRenderData pie = new ChartSingleSeriesRenderData();
        pie.setChartTitle("ChartTitle");
        pie.setCategories(new String[] { "俄罗斯", "加拿大", "美国", "中国" });
        pie.setSeriesData(new SeriesRenderData("countries", new Integer[] { 17098242, 9984670, 9826675, 9596961 }));
        data.put("pieChart", pie);
        render(data);

运行结果

其它图表使用参考官网。

7、pot-tl还有更多的功能、模板、示例代码可参考官网

  • 22
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在Spring Boot使用poi-tl库来导出带有合并列的Word表格并下载,您可以按照以下步骤操作: 1. 首先,确保您的Spring Boot项目已经添加了poi-tl的依赖。您可以在pom.xml文件添加以下依赖: ```xml <dependency> <groupId>com.deepoove</groupId> <artifactId>poi-tl</artifactId> <version>1.6.0</version> </dependency> ``` 2. 创建一个Controller来处理导出请求。例如,创建一个名为WordExportController的类,并添加一个处理导出请求的方法。 ```java import com.deepoove.poi.XWPFTemplate; import com.deepoove.poi.data.*; import com.deepoove.poi.util.BytePictureUtils; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableRow; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; @Controller public class WordExportController { @GetMapping("/export") public ResponseEntity<InputStreamResource> exportWord() throws IOException { // 创建一个数据模型 List<List<String>> tableData = new ArrayList<>(); tableData.add(createRow("Merged Cells", "Cell 3")); tableData.add(createRow("Cell 4", "Cell 6")); // 使用poi-tl的XWPFTemplate来生成Word文档 XWPFTemplate template = XWPFTemplate.compile("templates/template.docx").render( new DataTable(tableData) .setHeader(createRow("Header 1", "Header 2")) .setCellWidth(2000) // 设置单元格宽度 .setHeaderCellStyle(new CellStyle().setBold(true).setColor("FFFFFF").setBgColor("336699")) .setOddRowCellStyle(new CellStyle().setColor("FFFFFF").setBgColor("99CCFF")) .setEvenRowCellStyle(new CellStyle().setColor("FFFFFF").setBgColor("CCEEFF")) ); // 将生成Word文档转换为字节数组 ByteArrayOutputStream out = new ByteArrayOutputStream(); template.write(out); byte[] documentBytes = out.toByteArray(); // 设置下载响应的头信息 HttpHeaders headers = new HttpHeaders(); headers.setContentDispositionFormData("attachment", "merged_table.docx"); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); // 创建一个包含Word文档字节数组的InputStreamResource InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(documentBytes)); // 返回响应实体 return ResponseEntity.ok() .headers(headers) .body(resource); } private List<String> createRow(String cell1, String cell2) { List<String> row = new ArrayList<>(); row.add(cell1); row.add(cell2); return row; } } ``` 3. 在resources目录下创建一个名为template.docx的Word模板文件。在模板文件,您可以根据自己的需求设置表格样式和内容。 4. 启动您的Spring Boot应用程序,并访问导出请求的URL(例如:http://localhost:8080/export)。将会自动下载名为merged_table.docx的Word文档,其包含合并列的表格。 请确保按照您的需求修改代码,并根据模板文件的位置进行相应的调整。 希望对您有所帮助!如果您有任何其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霸道流氓气质

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值