Java使用XWPFTemplate将word填充数据,并转pdf

news2025/2/22 19:11:41

poi-tl

poi-tl(poi template language)是基于Apache POI的Word模板引擎。纯Java组件,跨平台,代码短小精悍,通过插件机制使其具有高度扩展性。

主要处理区域有这么几个模块:

依赖

<dependency>
            <groupId>com.deepoove</groupId>
            <artifactId>poi-tl</artifactId>
            <version>1.0.0</version>
            <exclusions>
                <exclusion>
                    <artifactId>slf4j-log4j12</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>

1、基本介绍

1.1、 根据文件路径、文件、文件流几种方式获取XWPFTemplate

//文件路径
XWPFTemplate template = XWPFTemplate.compile(wordtemplate).render(datas);

//文件
File wordtemplate = new File(inDocxFilePath);
XWPFTemplate template = XWPFTemplate.compile(wordtemplate).render(datas);

//文件流
InputStream wordtemplate = new FileInputStream(inDocxFilePath);
XWPFTemplate template = XWPFTemplate.compile(wordtemplate).render(datas);



1.2、生成到文件路径或者是流

//生成到文件路径
template.writeToFile(outFilePath);
template.close();


//生成到流
FileOutputStream out = new FileOutputStream(wordoutprint);
template.write(out);
out.flush();

//关闭资源
out.close();
template.close();

修改变量 为 ${var}

File inDocxFile = new File(inDocxFilePath);
Configure configure = Configure.newBuilder().buildGramer("${", "}").build();
XWPFTemplate template = XWPFTemplate.compile(inDocxFile, configure).render(map);

2、模板

2.1、文本、对象

TextRenderData、HyperLinkTextRenderData

Map<String, Object> map = new HashMap<>();
    // 1、普通字符
    map.put("word", "helloWord");

    //2、配置格式
    Style style = StyleBuilder.newBuilder().buildColor("00FF00").buildBold().build();
    map.put("author", new TextRenderData("HealerJean", style));

    //3、超链接
    map.put("website", new HyperLinkTextRenderData("website.", "http://www.baidu.com"));

    //制作模板
    XWPFTemplate template = XWPFTemplate.compile(wordtemplate).render(map);

    //开始生成新的word
    FileOutputStream outputStream = new FileOutputStream(outDocxFilePath);
    template.write(outputStream);
    outputStream.flush();

    //关闭资源
    outputStream.close();
    template.close();

2.2、图片

PictureRenderData

String imagePath = "D:/pdf/image.png";
    Map<String, Object> map = new HashMap<>();

    // 本地图片
    map.put("localPicture", new PictureRenderData(120, 120, imagePath));

    // 图片流文件
    InputStream inputStream = new FileInputStream(imagePath);
    map.put("localBytePicture", new PictureRenderData(100, 120, ".png", inputStream));

    // 网络图片
    map.put("urlPicture", new PictureRenderData(100, 100, ".png", BytePictureUtils.getUrlBufferedImage("https://raw.githubusercontent.com/HealerJean/HealerJean.github.io/master/assets/img/tctip/weixin.j跑pg")));

    // java 图片
    BufferedImage bufferImage = ImageIO.read(new FileInputStream(imagePath));
    map.put("bufferImagePicture", new PictureRenderData(100, 120, ".png", bufferImage));


    //如果希望更改语言前后缀为 ${var}
    Configure builder = Configure.newBuilder().buildGramer("${", "}").build();
    XWPFTemplate template = XWPFTemplate.compile(inDocxFilePath, builder).render(map);


    //开始生成新的word
    template.writeToFile(outDocxFilePath);
    template.close();

2.3、表格

MiniTableRenderData

Map<String, Object> map = new HashMap<>();

    Table table1 = new Table("11", "12", "13");
    Table table2 = new Table("21", "22", "23");
    List<Table> table = new ArrayList<>();
    table.add(table1);
    table.add(table2);

    // RowRenderData header = RowRenderData.build("one", "two", "three");
    //使用样式
    Style style = StyleBuilder.newBuilder().buildColor("00FF00").buildBold().build();
    RowRenderData header = RowRenderData.build(
        new TextRenderData("one", style), 
        new TextRenderData("two"), 
        new TextRenderData("three"));

    List<RowRenderData> tableBody = new ArrayList<>();
    for (Table item : table) {
        RowRenderData row = RowRenderData.build(
            item.getOne(), 
            item.getTwo(), 
            item.getThree());
        
        tableBody.add(row);
    }
    map.put("table", new MiniTableRenderData(header, tableBody));


    Configure builder = Configure.newBuilder().buildGramer("${", "}").build();
    XWPFTemplate template = XWPFTemplate.compile(inDocxFilePath, builder).render(map);
    template.writeToFile(outDocxFilePath);
    template.close();

2.4、列表模板

NumbericRenderData

Map<String, Object> map = new HashMap<>();

        map.put("unorderlist", new NumbericRenderData(
            new ArrayList<TextRenderData>()));
        map.put("orderlist", new NumbericRenderData
                (NumbericRenderData.FMT_DECIMAL, new ArrayList<TextRenderData>()));


        //如果希望更改语言前后缀为 ${var}
        Configure builder = Configure.newBuilder().buildGramer("${", "}").build();
        XWPFTemplate template = XWPFTemplate.compile(inDocxFilePath, 
                                                     builder).render(map);
        template.writeToFile(outDocxFilePath);
        template.close();

3、配置

ConfigureBuilder builder = Configure.newBuilder();
XWPFTemplate.compile("~/template.docx", builder.buid());

3.1、图片语法@修改为%

builder.addPlugin('%', new PictureRenderPolicy());

3.2、语法加前缀 为${var}

builder.buildGramer("${", "}");

3.3、模板标签设置正则表达式规则

模板标签支持中文、字母、数字、下划线的组合,比如,我们可以通过正则表达式来配置标签的规则,比如不允许中文:

builder.buildGrammerRegex("[\\w]+(\\.[\\w]+)*");

下面为我在工作中的应用:

生成word:

Map<String, Object> datas = new HashMap<String, Object>() {
{
//时间
put("year", year);
put(pNames[j] + "_" + vNames[j] + "_img_zhpf_4", new PictureRenderData(500, 300, pyhon_img_path + pNames[j] + "_" + vNames[j].replace("_", "-") + "_" + "comprehensive_score_" + element + "_4.png"));
}
};
XWPFTemplate template = XWPFTemplate.compile(wordtemplate).render(datas);
FileOutputStream out = new FileOutputStream(wordoutprint);
template.write(out);
out.flush();
out.close();
template.close();

转pdf:

public static boolean getLicense() {
        boolean result = false;
        try {
            File directory = new File("");// 参数为空
            String courseFile = directory.getCanonicalPath();//获取项目根目录
//            File file = new File("/temp/qh_assess/java_pro/config/license.xml"); // 新建一个空白pdf文档
            File file = new File(courseFile + "/config/license.xml"); // 新建一个空白pdf文档
            InputStream is = new FileInputStream(file); // license.xml找个路径放即可。
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static boolean doc2pdf(String inPath, String outPath) {
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return false;
        }
        try {
            long old = System.currentTimeMillis();
            File file = new File(outPath); // 新建一个空白pdf文档
            FileOutputStream os = new FileOutputStream(file);
            Document doc = new Document(inPath); // Address是将要被转化的word文档
            doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            // EPUB, XPS, SWF 相互转换
            long now = System.currentTimeMillis();
            System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

license.xml

<?xml version="1.0" encoding="UTF-8" ?>
<License>
    <Data>
        <Products>
            <Product>Aspose.Total for Java</Product>
            <Product>Aspose.Words for Java</Product>
        </Products>
        <EditionType>Enterprise</EditionType>
        <SubscriptionExpiry>20991231</SubscriptionExpiry>
        <LicenseExpiry>20991231</LicenseExpiry>
        <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
    </Data>
    <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>

这是默认生成的水印

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1799833.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【UE5教程】使用蓝图显示鼠标

首先&#xff0c;在您的项目中创建一个新的蓝图类&#xff0c;继承自PlayerController。在蓝图编辑器中&#xff0c;找到Event BeginPlay节点&#xff0c;并从它引出一条线。添加Set Show Mouse Cursor节点&#xff0c;勾选Visible&#xff0c;以确保鼠标在游戏开始时可见。 鼠…

flask_sqlalchemy时间缓存导致datetime.now()时间不变问题

问题是这样的&#xff0c;项目在本地没什么问题&#xff0c;但是部署到服务器过一阵子发现&#xff0c;这个时间会在某一刻定死不变。 重启uwsgi后&#xff0c;发现第一条数据更新到了目前最新时间&#xff0c;过了一会儿再次发送也变了时间&#xff0c;但是再过几分钟再发就会…

一句话说清HDMI ARC eARC功能和区别

HDMI&#xff1a; 高清多媒体接口&#xff0c;主要用于传输高清音视频信号&#xff0c;High Definition Multimedia Interface。 ARC: 音频回传通道&#xff0c;Audio Return Channel eARC: 增强型音频回传通道&#xff0c;第一个E是增强的意思&#xff0c;Enhanced Audio…

超过20W个高质量组件的开源PCB库

项目介绍 Celestial Altium Library是由Altium行业专家Mark Harris创建的一个庞大的免费开源数据库库&#xff0c;专为Altium Designer而设计&#xff0c;库中包含超过20万个优质组件 . 特点 高质量数据&#xff1a;Celestial Altium Library注重数据的质量&#xff0c;用户可…

聊聊二叉堆、红黑树、时间轮在定时任务中的应用

定时任务作为常用的一种调度方式&#xff0c;在各大系统得到了广泛的应用。 笔者也曾写过两篇关于定时任务框架介绍的文章&#xff1a; 《介绍一下,spring cloud下的另一种定时任务解决方案》《四叉堆在GO中的应用-定时任务timer》 之前都是以如何使用为主&#xff0c;这次从…

Dokcer 基础使用 (4) 网络管理

文章目录 Docker 网络管理需求Docker 网络架构认识Docker 常见网络类型1. bridge 网络2. host 网络3. container 网络4. none 网络5. overlay 网络 Docker 网路基础指令Docker 网络管理实操 其他相关链接 Docker 基础使用(0&#xff09;基础认识 Docker 基础使用(1&#xff09;…

Android无障碍服务

Hi I’m Shendi Android无障碍服务 最近想制作一个记录点击操作并重复播放的工具&#xff0c;用以解放双手&#xff0c;因现在的Android高版本基本上难以Root&#xff0c;所以选择了使用无障碍来实现&#xff0c;在这里记录下来。 Android无障碍 可参考文档&#xff1a;https:…

【MySQL】sql语句之库操作

序言 在上篇文章学习当中&#xff0c;我们认识了数据库的相关概念&#xff0c;以及MySQL的框架和基本使用等内容&#xff0c;总之对数据库有了一个大致的认识&#xff0c;那么本篇文章将开始关于sql语句的学习&#xff0c;本文主要是关于库的属性和操作的内容&#xff0c;简单可…

DOS 操作系统

DOS 介绍 DOS&#xff1a;disk operating system&#xff0c;磁盘操作系统。 中国DOS联盟下载 MS-DOS 7.10完整安装版&#xff08;含图形安装程序&#xff09; DOS 环境下的操作 输入部分内容后按下 Tab 可以快速自动补全。 按住 Ctrl 键可以用鼠标滚轮改变字号大小。 DO…

如何在virtualbox上安装Linux系统(centerOS)

提示&#xff1a;共同学习 注意&#xff1a;一定要在BIOS中的虚拟化打开。 文章目录 第一步&#xff1a; 第一步&#xff1a; 启动 、显示开启 centos基础安装 ​ ​

【传知代码】基于曲率的图重新布线(论文复现)

前言&#xff1a;在图形处理中&#xff0c;一个至关重要的问题是图形的重新布线&#xff0c;即在不改变图形基本结构的前提下&#xff0c;通过调整节点间的连接关系&#xff0c;使图形具有更好的性质&#xff0c;如更低的复杂度、更高的可视化效果或更强的鲁棒性。传统的图形重…

暂停系统更新

电脑左下角搜索注册表编辑器 计算机\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings 找到这个目录 打开FlightSettingsMaxPauseDays&#xff0c;没找到的话就创建一个同名文件夹然后选择10进制填入3550​​​​​​​ 最后进入系统暂停更新界面选择最下面…

[C/C++]_[初级]_[在Windows和macOS平台上导出动态库的一些思考]

场景 最近看了《COM本质论》里关于如何设计基于抽象基类作为二进制接口,把编译器和链接器的实现隐藏在这个二进制接口中,从而使用该DLL时不需要重新编译。在编译出C接口时,发现接口名直接是函数名,比如BindNativePort,怎么不是_BindNativePort?说明 VC++导出的函数默认是使…

Day49 动态规划part08

LC139单词拆分(未掌握) 未掌握分析&#xff1a;将字符串s中的各个字符看成是背包&#xff0c;思考成了多重背包问题单词就是物品&#xff0c;字符串s就是背包&#xff0c;单词能否组成字符串s&#xff0c;就是问物品能不能把背包装满。拆分时可以重复使用字典中的单词&#xf…

缓存方法返回值

1. 业务需求 前端用户查询数据时,数据查询缓慢耗费时间; 基于缓存中间件实现缓存方法返回值:实现流程用户第一次查询时在数据库查询,并将查询的返回值存储在缓存中间件中,在缓存有效期内前端用户再次查询时,从缓存中间件缓存获取 2. 基于Redis实现 参考1 2.1 简单实现 引入…

访问成员变量(反射)

文章目录 前言一、访问成员变量的方法二、Field类 1.常用方法2.实操展示总结 前言 为了实现随时随地调用某个类的某个成员变量&#xff0c;我们可以通过反射的Field类进行调用。这其中需要我们获取该类的Class对象&#xff0c;再调用Field类的相关方法&#xff0c;实时地灵活地…

虚拟机与windows文件同步

如果上图中不能设置&#xff0c;则在虚拟机mnt文件夹执行以下命令&#xff1a;

【Vue】作用域插槽

插槽分类 默认插槽&#xff1a;组件内定制一处结构 具名插槽&#xff1a;组件内定制多处结构 插槽只有两种&#xff0c;作用域插槽不属于插槽的一种分类。作用域插槽只是插槽的一个传参语法 作用&#xff1a; 定义slot 插槽的同时, 是可以传值的。给 插槽 上可以 绑定数据&a…

FL Studio21.2.9中文破解版水果软件安装包附带激活码注册码

音乐制作软件&#xff0c;对很多人而言&#xff0c;是一个“高门槛”的存在。它既需要专业的音乐知识&#xff0c;也需要复杂的操作技巧。 「FL Studio 21中文版马丁版下载」&#xff0c;复制整段内容&#xff0c;打开最新版「夸克APP」即可获取链接&#xff1a; https://pan…

Qt QProcess调用外部程序,并实时打印输出信息

Qt QProcess调用外部程序&#xff0c;并实时打印输出信息 引言一、源码分析1. 外部程序 - 被QProcess调用启动2. QProcessDemo - 调用外部程序&#xff0c;并实时打印输出信息 二、参考链接 引言 QProcess是Qt框架中的一个类&#xff0c;用于处理外部进程。它提供了一种直接与操…