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来输出文件。