1、word建好模板,需要填值的地方先写上标记词
2、另存为.xml文件格式的文件
3、用编辑器将需要填值的关键词用${xxx}替换,然后保存为.ftl文件。
4、新建一个map,key就是上面${}里面的字段。value就是需要填入word里的值
5、用freemarker中的Templeta类导入ftl模板并写入值
/**
* 输出到输出到文件
* @param ftlName ftl文件名
* @param root 传入的map
* @param outFile 输出后的文件全部路径
* @param ftlPath 模板的路径
*/
private static void printFile(String ftlName, Map<String,Object> root, String outFile, String ftlPath) throws Exception{
Writer out = null;
try {
File file = new File(outFile);
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
Template template = getTemplate(ftlName, ftlPath);
template.process(root, out); //模版输出
out.flush();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 通过文件名加载模版
* @param ftlName
*/
public static Template getTemplate(String ftlName, String ftlPath) throws Exception{
try {
Configuration cfg = new Configuration(); //通过Freemaker的Configuration读取相应的ftl
cfg.setEncoding(Locale.CHINA, "utf-8");
cfg.setDirectoryForTemplateLoading(new File(ftlPath)); //设定去哪里读取相应的ftl模板文件
Template temp = cfg.getTemplate(ftlName); //在模板文件目录中找到名称为name的文件
return temp;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
ps:如有问题欢迎指出!!!