java 通过poi操作word(doc)文件

通过POI类库实现word文档的创建。

思路:

通过自定义变量名,利用替换的方式,将所需数据填入,一般用于生成固定格式的报告。如果需要填入的数据很多,则略繁琐。

注意:

a)、例子中给的只能替换变量,不能根据结果生成多行数据。例如表格等。

b)、目前支持DOC格式,不支持DOCX格式

 

1、需要新建一个word模版,在需要输入数据的地方填入:

${变量名}

变量名称根据自行需要更改。不可有重复名称。

2、通过POI类,进行变量的替换,以实现word文件的生成。

3、示例:

public static void CreatWordByModel(String  tmpFile, Map<String, String> contentMap, String exportFile) throws Exception{

        InputStream in = null;
        in = new FileInputStream(new File(tmpFile));

        HWPFDocument document = null;
        document = new HWPFDocument(in);
        // 读取文本内容
        Range bodyRange = document.getRange();
        System.out.println(bodyRange.toString());
        System.out.println(bodyRange.text());
        // 替换内容
        for (Map.Entry<String, String> entry : contentMap.entrySet()) {
            bodyRange.replaceText("${" + entry.getKey() + "}", entry.getValue());
        }

        //导出到文件
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            document.write((OutputStream)byteArrayOutputStream);
            OutputStream outputStream = new FileOutputStream(exportFile);
            outputStream.write(byteArrayOutputStream.toByteArray());
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
}

public static void main(String[] args) throws Exception {
    Map map=new HashMap();
    map.put("data1","20190301");
    map.put("data2","你好");
    map.put("data3","这是一个测试");
    map.put("data4","CSDN");
    map.put("data5","https://blog.csdn.net/yxf771hotmail");
    CreatWordByModel("C:/model.doc",map,"C:/newfile.doc");
}

4、结果:

模版:

结果:

 

                                     打赏

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值