FreeMarker+XML實現寫word
public class XmlToExcel {
private static XmlToExcel tplm = null;
private Configuration cfg = null;
private XmlToExcel() {
cfg = new Configuration();
try {
//註冊tmlplate的load路徑
cfg.setClassForTemplateLoading(this.getClass(), "/template/");
} catch (Exception e) {
}
}
private static Template getTemplate(String name) throws IOException {
if(tplm == null) {
tplm = new XmlToExcel();
}
return tplm.cfg.getTemplate(name);
}
/**
*
* @param templatefile 模板文件
* @param param 需要填充的內容
* @param out 填充完成輸出的文件
* @throws IOException
* @throws TemplateException
*/
public static void process(String templatefile, Map param ,Writer out) throws IOException, TemplateException{
//獲取模板
Template template=XmlToExcel.getTemplate(templatefile);
template.setOutputEncoding("UTF-8");
//合併數據
template.process(param, out);
if(out!=null){
out.close();
}
}
public static void main(String[] args) {
//測試數據
Map<String,Object> param = new HashMap<String, Object>();
param.put("test","我的測試數據");
try {
Writer out = new OutputStreamWriter(new FileOutputStream(new File("d:\\test.doc")),"UTF-8");
XmlToExcel.process("test.xml", param,out);
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}
}
其實就是調用template的process方法來合併數據,然後freemarker通過writer來輸出文件。