org.apache.poi往word模板中填充数据(word2003)

Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。通过字面意思,我们大概知道这个API是可以用来做 java 导出word 及excel 的。

需求:现有一个空的word模板,通过代码往里面填充内容

空模板如下图所示:

填充后的文档内容如下:

代码如下:

public class WordModule {

    public static void main(String[] args) {
        Map map=new HashMap();
        map.put("version","1.0");
        map.put("number","9527");
        getBuild("static/doc/aa.doc",map,"D:/aaa.doc");
    }

    public static void getBuild(String  tmpFile, Map<String, String> contentMap, String exportFile){
        InputStream inputStream = WordModule.class.getClassLoader().getResourceAsStream(tmpFile);
        HWPFDocument document = null;
        try {
            document = new HWPFDocument(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

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

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

    }
}

Maven依赖:

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>3.9</version>
        </dependency>

参考博客:

java 使用word模板生成word

https://blog.csdn.net/qq_37838223/article/details/80484968

java poi 之 word 模板导出(1)

https://blog.csdn.net/ahutdbx/article/details/81326092

word版本为2003,高版本会报错:

报错解决方案参看博客:

Java导入Excel模版时出现org.apache.poi.poifs.filesystem.OfficeXmlFileException异常

https://blog.csdn.net/guo147369/article/details/78364543

猜你喜欢

转载自blog.csdn.net/u013517229/article/details/89153524