使用java生成word文档的方法

2024-10-15 05:42:55

1、引入freemark的jar包,因为需要利用freemark里的方法进行转换在pom.xml文件中加入<depende荏鱿胫协ncy> <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文档的方法
猜你喜欢