使用poi的hwpf模块操作word文档模版生成想要的文档 demo

 

demo地址:https://gitee.com/ohaha123/poi_hwpf_demo

 

一,引入mavn

按照下面的依赖实测可以,不然会有各种问题,找不到类 找不到方法的都错误都出现过。

<poi.version>4.1.2</poi.version>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>${poi.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>${poi.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>${poi.version}</version>
</dependency>

二、编写代码

 

下面的方法会替换模版文件,而不会丢下你原来的格式,比如模版中是有下划线的 ,替换后还保留下划线,网上找了好多例子样式都是奇奇怪怪的。试了多次之后只有下面的方法能到达预期的效果。

replaceDoc方法

/**
     *
     * @param inUrl 模版文件路径
     * @param outUrl 输出文件路径
     * @param params 参数
     * @throws Exception
     */
    public static void replaceDoc(String inUrl,String outUrl,Map<String,String> params) throws Exception {
        FileInputStream in1 = new FileInputStream(inUrl);
        HWPFDocument doc = new HWPFDocument(in1);

        Range range = doc.getRange();
        for (Map.Entry<String,String> entry:
                params.entrySet()) {
            range.replaceText(entry.getKey(), entry.getValue());
        }


        // 另存模板文件为exportTestg.doc
        FileOutputStream out = new FileOutputStream(outUrl);
        doc.write(out);
        out.flush();
        out.close();
    }

 

三、看看效果

文档模版:

生成的文档效果

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值