利用模板导出word文档

最近研究了一下用freemarker导出word的例子,记录一下方便大家学习,利用模板的好处是可以控制word的样式。

1.将处理好的的word模板,另存为xml格式的文档。并在其中添加参数: ${export}
2.2.将xml文档修改完成后,保存并修改后缀名为“*.ftl”;
3.编写java类实现赋值和处理流(抱歉代码没有写注释)

public class TempltUtil {

public static final String WORD_TEMPLATE = "/test.ftl";
public static final String TEMPLATE_PATH = "/vm";
public static final String PREVIEW_DOC = "/pr.doc";

public static Template configTemplate(HttpServletRequest request, String temp) throws IOException {
Configuration config = new Configuration();
ServletContext sc = request.getSession().getServletContext();
config.setDirectoryForTemplateLoading(new File(sc.getRealPath(TEMPLATE_PATH)));
config.setObjectWrapper(new DefaultObjectWrapper());
Template template = config.getTemplate(temp, "UTF-8");
return template;
}

public static void toPreview(HttpServletRequest request, String temp, Map<?, ?> root){
try {
String previewPath = request.getSession().getServletContext().getRealPath("")+PREVIEW_DOC;
Template template = configTemplate(request, temp);
FileOutputStream fos = new FileOutputStream(previewPath);
Writer out = new OutputStreamWriter(fos, "UTF-8");
template.process(root, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}


4.填充数据
 private boolean getData(HttpServletResponse response,HttpServletRequest request,Map dataMap) {  

dataMap.put("title_name", "用户信息");

dataMap.put("user_name", "张三");

dataMap.put("org_name", "xx公司");

dataMap.put("dept_name", "事业部");
TempltUtil.toPreview(request, TempltUtil.WORD_TEMPLATE, dataMap);
return true;

}


5.前台调用的导出方法
 @RequestMapping(value="exportWord")
public void excWord(HttpServletResponse response,HttpServletRequest request) throws IOException{


try {
Map dataMap = new HashMap();
if (getData(response,request,dataMap)) {
File previewFile = new File(request.getSession().getServletContext().getRealPath(TempltUtil.PREVIEW_DOC));
InputStream is = new FileInputStream(previewFile);
response.reset();
response.setContentType("application/vnd.ms-word;charset=UTF-8");
response.addHeader("Content-Disposition","attachment; filename=\"" + TempltUtil.PREVIEW_DOC + "\"");
byte[] b = new byte[1024];
int len;
while ((len=is.read(b)) >0) {
response.getOutputStream().write(b,0,len);
}
is.close();
response.getOutputStream().flush();
response.getOutputStream().close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值