public classFreemarkerUtil {private static final Object LOCK = newObject();/**
* word文件*/
public static final int WORD_FILE = 1;/**
* excel文件*/
public static final int EXCEL_FILE = 2;private staticConfiguration cfg;private staticFreemarkerUtil ftl ;privateFreemarkerUtil(String templateFolder) throws IOException {
cfg= newConfiguration();
cfg.setDirectoryForTemplateLoading(newFile(templateFolder));
cfg.setObjectWrapper(newDefaultObjectWrapper());
}private static voidcheck(HttpServletRequest request) {if (ftl == null) {
synchronized (LOCK) {try{
ftl= new FreemarkerUtil(request.getServletContext().getRealPath("/")+"export/template");
}catch(IOException e) {
e.printStackTrace();
}
}
}
}/**
* 创建 word 文档
* 必须先设置response导出配置,然后解析模版,否则会出问题
* @throws IOException*/
public static void createFile(String templateName,String docFileName, Map rootMap,HttpServletRequest request, HttpServletResponse response,intfileType) throws IOException {//response.resetBuffer();//设置导出
response.addHeader("Cache-Control","no-cache");
response.setCharacterEncoding("UTF-8");if( WORD_FILE ==fileType){
response.setContentType("application/vnd.ms-word;charset=UTF-8");
}else if(EXCEL_FILE ==fileType){
response.setContentType("application/octet-stream;charset=UTF-8");
}else{
response.setContentType("application/octet-stream");
}
String ua= request.getHeader("user-agent");
ua= ua == null ? null: ua.toLowerCase();if(ua != null && (ua.indexOf("firefox") > 0 || ua.indexOf("safari")>0)){try{
docFileName= new String(docFileName.getBytes(),"ISO8859-1");
response.addHeader("Content-Disposition","attachment;filename=" +docFileName);
}catch(Exception e) {
}
}else{try{
docFileName= URLEncoder.encode(docFileName, "utf-8");
response.addHeader("Content-Disposition","attachment;filename=" +docFileName);
}catch(Exception e) {
}
}
check(request);//解析模版
Template temp = cfg.getTemplate(templateName, "UTF-8");
PrintWriter write=response.getWriter();try{
temp.process(rootMap, write);
}catch(TemplateException e) {
e.printStackTrace();
}finally{if(write != null){
write.flush();
write.close();
}
}
}
}