首先,需要准备一个Word(.doc或者.docx)文档的模版,把里面需要动态插入的数据写成以英文开头的字符串,例如:
第二步:把这个word模版另存为2003的xml文件,然后打开,把里面对应的英文字符串改成 ${英文字符串} 的形式(例如:${d1}),用于动态插入。
第三步:把修改好的xml文件的后缀名直接改成ftl。(这就是程序用的真正模版)
第四步,写代码:
package com.canglang.etc.gpsm.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import com.opensymphony.xwork2.ActionContext;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class ToWordDocumentAction {
public void exportObj() {
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
Map<String,Object> dataMap=new HashMap<String,Object>();
dataMap.put("xitongmingcheng", "对应数据");
dataMap.put("xitongbianhao", 1);
dataMap.put("yewumiaoshu", "对应数据");
dataMap.put("fuwufanwei", "对应数据");
dataMap.put("dengjipingcedanweimingcheng", "对应数据");
dataMap.put("heshitouruyunxinshiyong", "对应数据");
dataMap.put("shangjixitongmingcheng", "对应数据");
dataMap.put("shangjixitongsuoshudanweimingcheng", "对应数据");
configuration.setClassForTemplateLoading(this.getClass(), "/com/canglang/etc/template"); //FTL文件所存在的位置
Template t = null;
try {
t = configuration.getTemplate("workModel.ftl"); //文件名
t.setEncoding("utf-8");
} catch (IOException e) {
e.printStackTrace();
}
String fileName = systemBasicInformation.getSystemName() + ".doc";
ActionContext ctx = ActionContext.getContext();
HttpServletResponse response = (HttpServletResponse) ctx
.get("com.opensymphony.xwork2.dispatcher.HttpServletResponse");
response.setContentType("application/msword");
try {
response.addHeader("Content-Disposition", "attachment; filename="
+ URLEncoder.encode(fileName, "UTF-8"));
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
t.process(dataMap, out);
out.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}
}