1、模板文件采用xml形式,比如word可以另存为xml格式文件,目前已知模板文件可以是xml、html、jsp等,生成模板要注意,尽量用低版本的软件来生成xml模板。
java示例代码,读取D:/workspace/testWebService/WebRoot/resource/template目录的模板,动态生成word,动态设置word内容中的姓名、性别、爱好
package com.fxf.util;
import java.io.BufferedWriter;import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class FreeMarkerUtil {
//模板存放目录
private final static String templateDir = "D:/workspace/testWebService/WebRoot/resource/template";
//生成文件目录
private final static String outFile = "D:/workspace/testWebService/WebRoot/resource/tmp/";
/**
* 从D:/workspace/testWebService/WebRoot/resource/template路径获取指定模板
* @param templateName
* @return Template
*/
public static Template getFreeMarkerTemplate(String templateName) {
Template template = null;
try {
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
configuration.setDirectoryForTemplateLoading(new File(templateDir));
//根据名称获取模板
template = configuration.getTemplate(templateName);
} catch (IOException e) {
e.printStackTrace();
}
return template;
}
/**
* @param args
*/
public static void main(String[] args) {
//根据模板名称获取模板
Template template = getFreeMarkerTemplate("模板标题.xml");
//设置数据,map的key与模板中的key一致
Map map = new HashMap();
map.put("name", "王五");
map.put("sex", "女");
map.put("like", "篮球");
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outFile + System.currentTimeMillis() + ".doc"), "UTF-8"));
//生成文件,并将数据填充到文件中
template.process(map, out);
out.flush();
out.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}