---
title: "利用模板导出word文档"
author: "xihuan&java"
date: "2014-02-20T16:54:29Z"
tags: []
categories: ["Web前端"]
slug: "word"
draft: false
lastmod: "2014-02-20T17:11:50Z"
id: 2019870
url: "https://wdwheyr.iteye.com/blog/2019870"
---

最近研究了一下用freemarker导出word的例子，记录一下方便大家学习，利用模板的好处是可以控制word的样式。

1.将处理好的的word模板，另存为xml格式的文档。并在其中添加参数：  ${export}
2.2.将xml文档修改完成后，保存并修改后缀名为“*.ftl”;
3.编写java类实现赋值和处理流（抱歉代码没有写注释）

```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.填充数据

```java
 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.前台调用的导出方法

```java
 @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(); 
    		} 
    }
```