码迷,mamicode.com
首页 > 编程语言 > 详细

java导出word直接下载

时间:2014-12-15 15:07:55      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   使用   sp   

导出word工具类

package util;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class ExportWordUtil {
    
    private static final Logger log = LoggerFactory.getLogger(ExportWordUtil.class);

    /**
     * 导出word文档
     * @param response
     * @param fileName 下载文件名称
     * @param model 模板名称
     * @param dataMap 导出数据
     */
    public static void createDoc(HttpServletResponse response, String fileName, String model, Map<String,Object> dataMap) {
        response.setContentType("application/x-download;charset=UTF-8");
        try {
            fileName = new String(fileName.getBytes("GBK"),"ISO-8859-1");
        } catch (Exception e) {
            log.error("文件名编码出错!");
        }
        //给文件名加上时间戳
        fileName += DateTimeUtils.getNowTimeShortString() + ".doc";
        response.addHeader("Content-disposition", "filename="+fileName+";charset=UTF-8");
        //设置模本装置方法和路径,默认指定在/resources/exportWord目录下
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("UTF-8");
        configuration.setClassForTemplateLoading(ExportWordUtil.class, "/resources/exportWord");
        Template template = null;
        try {
            //装载模板
            template = configuration.getTemplate(model);
            template.setEncoding("UTF-8");
        } catch (IOException e) {
            log.error("导出word装载模版出错!");
            e.printStackTrace();
        }
        Writer out = null;
        try {
            //输出对象,并对文件名进行编码
            out = response.getWriter();
        } catch (IOException e) {
            log.error("导出word输出流创建错误!");
            e.printStackTrace();
        }
        try {
            //装载并输出数据,生成word文档
            template.process(dataMap, out);
        } catch (TemplateException e) {
            e.printStackTrace(); 
            log.error("导出word出错!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

如何在action中使用:

    /**
     * 导出
     * @param id
     * @param response
     * @return
     */
    @RequestMapping("/util/export.do")
    public void export(HttpServletResponse response) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("xm", "小花猫");
     daaMap.put("age", "3"); ExportWordUtil.createDoc(response,
"小花猫信息", "xhmxx.ftl", dataMap); }

 

java导出word直接下载

标签:style   blog   http   io   ar   color   os   使用   sp   

原文地址:http://www.cnblogs.com/baifeilong/p/4164793.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!