栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA POI实现Word填充(DOC)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA POI实现Word填充(DOC)

这种填充技术后的文件是doc格式的可以下载word中的文本样式。

    导入两个必须的Jar包:poi-3.10.1.jar和poi-scratchpad-3.10.1.jar

    如果报filesystem错误,应该是引用的这两个包的版本不一样,所以一定要保持版本一致。

    直接将内容导出成DOC文件:

     public static int exportDoc(String destFile,String fileContent){

    try {

    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(fileContent.getBytes("UTF-8"));

    POIFSFileSystem fileSystem = new POIFSFileSystem();

    DirectoryEntry directory = fileSystem.getRoot();

    directory.createdocument("Worddocument", byteArrayInputStream);

     FileOutputStream fileOutputStream = new FileOutputStream(destFile);

    fileSystem.writeFilesystem(fileOutputStream);

    byteArrayInputStream.close();

    fileOutputStream.close();

     return 1;

    } catch (IOException e) {return 0;

     }

    }

    这个导出只是对文字Word做的导出。

    用法:

    exportDoc("C:\12.doc", "exportDoc导出Word");

    使用模板导出Doc的话需要先定义好模板内容。

    例如模板内容如下图所示。

        public static HWPFdocument replaceDoc(String templatePath, Map contentMap) {

            try {

                // 读取模板

    FileInputStream tempFileInputStream = new FileInputStream(new File(templatePath));

    HWPFdocument document = new HWPFdocument(tempFileInputStream);

                // 读取文本内容

                Range bodyRange = document.getRange();

                // 替换内容

                for (Map.Entry entry : contentMap.entrySet()) {

                    bodyRange.replaceText("${" + entry.getKey() + "}", entry.getValue());

                }

                return document;

            } catch (Exception e) {

                return null;

            }

        }

    调用方法如下:

    Map contentMap=new HashMap();

    contentMap.put("name", "飞翔家族");

    contentMap.put("age", "123");

    contentMap.put("email", "1231231231@123.com");

    HWPFdocument document = replaceDoc("C:\template.doc", contentMap);

            if(document != null){

             ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

                try {

                    document.write(byteArrayOutputStream);

                    OutputStream outputStream = new FileOutputStream(destFile);

                    outputStream.write(byteArrayOutputStream.toByteArray());

                    outputStream.close();

                } catch (IOException e) {                            }

            }

    使用模板导出DOC文件我们还可以使用其他的方法。

    我们还是先需要制作好DOC模板文件,然后另存为XML文件。

    使用velocity,将数据填充,导出成DOC文件。

    这里介绍的都是最简单的方法,直接导出文本Word,如果要导出复杂一点的Word,请再查阅。
     

    读取doc文件的内容

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/759830.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号