使用freemarker实现word导出

1,下载freemarker架包。
2,使用word绘制一个导出后的模板,其中${}写入自己所对应的实体类字段或是自己取到的键值数据(对应下面的map)
这里写图片描述
3.将上面的word另存为.xml文件,然后重命名将后缀.xml 改为 .ftl(右键重命名时没后缀是电脑没设置后缀显示)
4.被控制层调用类DocumentHandler .class的代码如下:

public class DocumentHandler {


private Configuration configuration = null;  

    public DocumentHandler() {  
        configuration = new Configuration();  
        configuration.setDefaultEncoding("utf-8");  
    }  

    /**
     * @desc  导出doc文件 -- 到本地电脑
     * @author MrC
     * @param dataMap 要填入模本的数据文件  
     * @param templatePath 模板路径 
     * 模板路径 如:String templatePath = request.getServletContext().getRealPath("/") + File.separator + "exportTemplate";
     * @param templateName 模板名 如:freeMarkTemplate.ftl
     * @throws Exception
     */
    public void createDoc(Writer out,Map<String,Object> dataMap,String templatePath,String templateName) throws Exception {  
    //设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,  
    configuration.setDirectoryForTemplateLoading(new File(templatePath));  
        Template t=null;  
        try {  
            //test.ftl为要装载的模板  + File.separator + "freeMarkTemplate.ftl"
            t = configuration.getTemplate(templateName);  
        } catch (IOException e) {  
            e.printStackTrace();  
        } 

        try {  
            t.process(dataMap, out);  
            out.close();  
        } catch (TemplateException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    } 

    /**
     * @desc  导出doc文件 --至指定路径下
     * @author MrC
     * @param dataMap 要填入模本的数据文件  
     * @param templatePath 模板路径 
     * 模板路径 如:String templatePath = request.getServletContext().getRealPath("/") + File.separator + "exportTemplate";
     * @param templateName 模板名 如:freeMarkTemplate.ftl 
     * @param fileName 下载路径 
     * 下载路径 如:String templatePath = request.getServletContext().getRealPath("/") + File.separator + "outFile.doc";
     */
    public void createDoc2(Map<String,Object> dataMap,String templatePath,String templateName,
    String filePath,String fileName) throws Exception {  
    //设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,  
        configuration.setDirectoryForTemplateLoading(new File(templatePath)); 
        Template t=null;  
        try {  
            //test.ftl为要装载的模板  + File.separator + "freeMarkTemplate.ftl"
            t = configuration.getTemplate(templateName);  
        } catch (IOException e) {  
            e.printStackTrace();  
        } 

        File file = new File(filePath);
if (!file.exists()) { //判断文件夹是否存在,如果不存在则创建文件夹
file.mkdirs();
}

        //输出文档路径及名称  
        File outFile = new File(filePath + File.separator + fileName);  
        Writer out = null;  
        FileOutputStream fos=null;  
        try {  
            fos = new FileOutputStream(outFile);  
            OutputStreamWriter oWriter = new OutputStreamWriter(fos,"GBK");  
            //这个地方对流的编码不可或缺,使用main()单独调用时,应该可以,但是如果是web请求导出时导出后word文档就会打不开,并且包XML文件错误。主要是编码格式不正确,无法解析。  
            //out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));  
             out = new BufferedWriter(oWriter);   
        } catch (FileNotFoundException e1) {  
            e1.printStackTrace();  
        }  

        try {  
            t.process(dataMap, out);  
            out.close();  
            fos.close();  
        } catch (TemplateException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}

5.控制层代码:

//dataMap用来存储你将要导出的数据
  Map<String,Object>  dataMap = new HashMap<String,Object>;

  //这里的volunteerId对应上面word中的${volunteerId},volunteerDto是我自己的实体类,以下为事例代码
  dataMap.put("volunteerId",volunteerDto.getVolunteerId);

  DocumentHandler mdoc = new DocumentHandler();
        //获取模板路径
String templatePath = request.getSession().getServletContext().getRealPath("")+"/wordTemplate";
//模板名字
String templateName="volunteer.ftl";
//取得请求头
response.setContentType("application/x-msdownload");
response.setCharacterEncoding("utf-8");
String fileName="数据加载错误";
//设置导出名字
if(volunteerDto.getUserName()!=null&&volunteerDto.getCertifNo()!=null){
fileName = volunteerDto.getUserName()+"+"+volunteerDto.getCertifNo()+".doc";
}
response.setHeader("content-disposition", "attachment;filename="+new String(fileName.getBytes("gb2312"), "ISO8859-1"));
//调用导出方法
mdoc.createDoc(response.getWriter(),dataMap,templatePath,templateName);

6.以上代码可实现页面下点击导出按钮,如果导出出现word文档内容错误而打不开,很可能是编码不统一

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值