过了几天再看这篇文章感觉自己写的也太不走心的,本渣渣决定好好解释一下( ̄▽ ̄)"
加载模板的三种方法我觉得下面那个连接中大家都可以看懂我就之所以下模板的流程吧
- 先建一个word文档根据画出你想要的模板
- 在此框中填入代码如 ${nation} nation可以换成别的,但是一定要保证到时候传参的时候要一致
- 将所有需要替换的位置都用代码替换后,将该文件转成ftl文件,将ftl文件放在项目中
- 可以将我下面的代码复制到你的函数中,修改相应的参数
十分感谢下面链接的作者,笔芯
https://blog.youkuaiyun.com/gtlishujie/article/details/52300381
Configuration cfg = new Configuration();
try {
FileSystemView fsv = FileSystemView.getFileSystemView();
// 将桌面的那个文件目录赋值给file
File file = fsv.getHomeDirectory();
// 输出桌面那个目录的路径
String dir = file.getPath();
System.out.println(dir);
cfg.setClassForTemplateLoading(this.getClass(), "/test0827");//模板所在位置
Template template = cfg.getTemplate("test.ftl"); //framemaker.ftl为要装载的模板
// 设置对象包装器
cfg.setObjectWrapper(new DefaultObjectWrapper());
// 设置异常处理器
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
// 定义数据模型
Map<String, String> root = new HashMap<String, String>();
root.put("nation", "汉"); //将 汉 替换原来 ${nation}的位置
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(dir+"/out.doc"))); //文件所储存的位置
try {
// 解释模板
template.process(root, out); //将 名为root的Map 映射到 out 输出中
} catch (TemplateException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
模板中:
民族 ${nation}
结果:
民族汉
模板为ftl文件