标签: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); }
标签:style blog http io ar color os 使用 sp
原文地址:http://www.cnblogs.com/baifeilong/p/4164793.html