使用java生成word文档的方法

2025-11-03 20:31:08

1、引入freemark的jar包,因为需要利用freemark里的方法进行转换

在pom.xml文件中加入

<dependency>

    <groupId>org.freemarker</groupId>

    <artifactId>freemarker</artifactId>

    <version>2.3.23</version>

</dependency>

使用java生成word文档的方法

2、新建一个WordTest测试类

Map<String,String> dataMap = new HashMap<String,String>();

dataMap.put("name", "Tom");

dataMap.put("age", "20");

dataMap.put("province", "江苏");

Configuration configuration = new Configuration();

configuration.setDefaultEncoding("utf-8");

configuration.setDirectoryForTemplateLoading(new File("F:\\apps\\test"));

// 输出文档路径及名称

File outFile = new File("F:\\apps\\test\\test-gen.doc");

//以utf-8的编码读取ftl文件

Template t =  configuration.getTemplate("test.xml","utf-8");

Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"),10240);

t.process(dataMap, out);

out.close();

使用java生成word文档的方法

3、在自己指定一个目录(F:\apps\test)下新建一个模版word文档,填写自己需要的模版格式

姓名:${name}

年龄:${age}

省份:${province}

使用java生成word文档的方法

4、然后将word另存为xml文件,不要直接修改后缀,使用另存为的方式

使用java生成word文档的方法

5、运行测试类的genWord方法,打印信息提示生成成功

使用java生成word文档的方法

6、去F:\apps\test目录查看生成的word文档,打开之后可以看到java中赋的值已经填入到word中

使用java生成word文档的方法

使用java生成word文档的方法

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢