第一部分:制作模板
1、首先在word里面编辑好你的内容,把你需要动态替换的地方用变量(如下面的${name})替换掉,将来用Map类型传参数。将文件保存为xml格式。模板做好了。
2、用文本编辑工具(UtrlEidt, EditPlus等)打开检查变量表达式是否完整。即${name}在一起,不是分开的${ 内容 name}。然后将文件保存为*.ftl 文件。
注意:有个小技巧,在word里输入${name}之前,先在其他地方如记事本里面写,然后完整的粘贴过来,这样生成的xml文件变量完 好。
第二部分;java代码
1、下载freemarker jar包
http://mvnrepository.com/artifact/org.freemarker/freemarker/2.3.22
(注:下载jar包可以去这个网站:http://mvnrepository.com/ ,很方便,很全)
2、在web项目的使用我就不说了,(主要两种,一、引用build path... 二、放到项目的lib下)
3、贴段代码,是不是很少,这足够了,使用的时候调用createDoc方法即可,需要注意的是第二个
参数是outputStream类型,传参数时用response.getoutputStream() 即可。
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateNotFoundException;
@SuppressWarnings("deprecation")
public class WordGenerator {
private static Template template = null;
static {
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");//qyws-jzzf/src/main/resources/com/wondersgroup/qyws/jzzf/vaccine/tzd.ftl
configuration.setClassForTemplateLoading(WordGenerator.class, "");
try {
template = configuration.getTemplate("tzd.ftl");
} catch (TemplateNotFoundException e) {
e.printStackTrace();
} catch (MalformedTemplateNameException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void createDoc(Map<?, ?> dataMap, OutputStream os) {
try {
Writer w = new OutputStreamWriter(os, "utf-8");
template.process(dataMap, w);
w.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
4、测试代码:在使用的地方可以填充以下代码。
Map<String, Object> map = new HashMap<String, Object>();
String n = "小明";
map.add("name", n );
try {
response.setContentType("application/msword");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("名字".doc", "utf-8"));
ServletOutputStream out = response.getOutputStream();
WordGenerator.createDoc(map, out);
out.flush();
out.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
5、结果:
你好小明,今天天气很好!
其他参见转载:http://blog.csdn.net/jackfrued/article/details/39449021