java 通过poi操作word(doc)文件 - Go语言中文社区

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、结果:

模版:

结果:

 

                                     打赏

 

 

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/yxf771hotmail/article/details/88310423
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2019-08-26 22:57:42
  • 阅读 ( 1707 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢