此案例使用簡單的map,如需要使用更高級的請使用實體類封裝,原理相同,最終需要的是map類型的數據,無論是list都一樣
list<Map<String,Object>> list =new HashMap<Map<String,Object>>();
在項目開發中生成xml,xb,html,word的入門首選,理解是關鍵。至於生成複雜的xml,xb結構的數據,在word中動態生成列等案例後續補充
1.導入freemarker的jar包
2.書寫代碼和模板文件
3.運行
1.代碼
package com.freemarker;import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class TestFreemarker {
public static void main(String[] args) {
try {
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
configuration.setDirectoryForTemplateLoading(new File("D:\\develop\\testdemo\\src\\com\\freemarker"));
Template template = configuration.getTemplate("template.ftl");
Map<String,String> map = new HashMap<String,String>();
map.put("username", "zhangsan");
map.put("password", "123456");
File file = new File("D:\\test.xml");
BufferedWriter out = new BufferedWriter(new FileWriter(file));
template.process(map, out);
out.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2.模板template.ftl文件內容
<?xml version="1.0" encoding="UTF-8"?>
<p:a ${username}></p:a>
<td>${password}</td>