以实现简单的word导出:
然后将word另存为.xml文件,打开文件,找到title将其修改为${title},后面要替换的内容依次替换掉。然后将.xml文件后缀改为.ftl,导入.ftl模板文件到指定目录。加载jar包freemarker.jar。
代码如下:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsISM9AnYldnJwAzN9c3Pml2Zu0GbyoVdzJTW2hXbRtmVHRmaG12YwUjMiRUO5NWe5cEZo50VhtWNXNlb1cVY1x2RiBjVzQldwIjYqVTej5WOHJWa1ITW11EWa5mRXJGc5kHT20ESjBjUIF2Lc12bj5SYphXa5VWen5WY35iclN3Ztl2Lc9CX6MHc0RHaiojIsJye.gif)
1 import java.io.BufferedWriter;
2 import java.io.File;
3 import java.io.FileOutputStream;
4 import java.io.OutputStreamWriter;
5 import java.io.Writer;
6 import java.net.URLDecoder;
7 import java.util.HashMap;
8 import java.util.Map;
9
10 import freemarker.template.Configuration;
11 import freemarker.template.Template;
12 import freemarker.template.Version;
13
14 public class WordUtil {
15
16 public static void main(String[] args) {
17 // 替换的数据词典
18 Map<String, Object> dataMap = new HashMap<String, Object>();
19 dataMap.put("date", "2020年8月");
20 dataMap.put("maxTemp", "非洲,南美洲");
21 dataMap.put("minTemp", "非洲,南美洲sss");
22 wordOutput(dataMap, "test.ftl", "D:/t.doc");
23 }
24
25 public static void wordOutput(Map<String, Object> dataMap, String sourceName, String targetPath) {
26 try {
27 // Configuration 用于读取ftl文件
28 Configuration configuration = new Configuration(new Version("2.3.28"));
29 configuration.setDefaultEncoding("utf-8");
30
31 /**
32 * 以下是两种指定ftl文件所在目录路径的方式,注意这两种方式都是 指定ftl文件所在目录的路径,而不是ftl文件的路径
33 */
34 // 指定路径的第一种方式(根据当前类的相对路径指定)
35 // configuration.setClassForTemplateLoading(WordUtil.class, "");
36
37 // 指定路径的第二种方式,获取项目中resources目录下的文件
38 String resourcesPath = WordUtil.class.getResource("/").getPath();
39 // 处理路径中的中文乱码问题
40 String path = URLDecoder.decode(resourcesPath, "utf-8");
41 System.out.println(path);
42 configuration.setDirectoryForTemplateLoading(new File(path));
43
44 // 输出文档路径及名称
45 File outFile = new File(targetPath);
46
47 // 以utf-8的编码读取ftl文件
48 Template template = configuration.getTemplate(sourceName, "utf-8");
49 Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
50 template.process(dataMap, out);
51 out.close();
52 } catch (Exception e) {
53 e.printStackTrace();
54 }
55 }
56 }
View Code
模板存放位置:文档模板存放在项目的resource下,方便打包和整洁
这个地方尝试了很久,才获取到项目的resource目录,当然也可以直接指定本地磁盘的目录
// 指定路径的第二种方式,获取项目中resources目录下的文件
String resourcesPath = WordUtil.class.getResource("/").getPath();
// 处理路径中的中文乱码问题
String path = URLDecoder.decode(resourcesPath, "utf-8");
System.out.println(path);
configuration.setDirectoryForTemplateLoading(new File(path));
文档模板存放截图: