导入freemarker依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
完成Word导出模版
- 新建word文档。
- 将word文档另存为xml文件。(不能直接修改扩展名)
- 将xml文件的扩展名改为ftl
后台代码部分
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.*;
import java.util.*;
public class ToWord {
public static void main(String[] args) {
Map<String, String> map = new HashMap();
map.put("name","尼古拉斯赵四");
map.put("phone","123456789");
map.put("birth","2020年11月24日");
map.put("sex","男");
map.put("age","3");
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
try {
configuration.setDirectoryForTemplateLoading(new File("G:/"));
File outFile = new File("G:/test.doc");
Template t = configuration.getTemplate("test.ftl","utf-8");
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"),10240);
try {
t.process(map, out);
} catch (TemplateException e) {
e.printStackTrace();
}
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
效果展示
可能出现的异常
解决方法:
- 再次将word文档另存为xml文件,然后修改xml后缀为ftl。
- 若还是出现该异常,则使用记事本等工具打开xml文件,检查每个${},很有可能在word文档转xml时出现了问题。