java+springmvc實現根據freemarker模板導出word模板。模板使用的后綴可以是:.xml,也可以是.ftl。
步驟1,引入freemarker的jar包。
步驟2,制作模板文件。(紅框中的內容是為了替換使用)
另存為xml格式,
找到xml文件,右鍵用editplus打開,找到紅框的標記1,標記2進行修改。
如果是表格的話,表頭的第一行需要保留。
表格的主體部分需要保留一個,
這里eList是從后台賦值的一個集合,${e_index+1}是根據<#list eList as e>這個別名+_index得到,用法基本與el表達式用法相同。
這樣一個模板就完成了,將模板復制進項目中即可,后綴是什么不重要,重要的是我們用freemarker解析。
步驟4,java后台代碼。
@RequestMapping("/test/toWord") public ModelAndView toWord(HttpServletRequest request, HttpServletResponse response) throws IOException{ File file = createDoc(); response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("UTF-8"); java.io.BufferedInputStream bis = null; java.io.BufferedOutputStream bos = null; try { long fileLength = file.length(); response.setContentType("application/msword"); response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("測試的,統計-導出時間"+DateTimeUtils.getDateTime("yyyyMMddHHmmss")+".doc", "utf-8")); response.setHeader("Content-Length", String.valueOf(fileLength)); bis = new BufferedInputStream(new FileInputStream(file)); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); } return null; } private File createDoc(){ // 創建數據 Map<String,Object> dataMap = new HashMap<String, Object>(); dataMap.put("cwlx", "測試的"); List<?> eList = new ArrayList<?>();// 這里是獲取list列表的方法 dataMap.put("czsj",DateTimeUtils.getDateTime("yyyyMMddHHmmss"));// 這里是獲取當前時間的一種方式,可以根據自己程序自行修改 dataMap.put("eList", eList); // 獲取模板 Configuration configuration = new Configuration(); configuration.setDefaultEncoding("utf-8"); configuration.setClassForTemplateLoading(this.getClass(), "/tpl"); Template t = null; String name = "temp"+(int)(Math.random()*1000)+".doc"; File file = new File(name); try { t = configuration.getTemplate("model.xml"); t.setEncoding("UTF-8"); Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name),"UTF-8")); t.process(dataMap, out); out.close(); } catch (IOException e) { e.printStackTrace(); } catch (TemplateException e) { e.printStackTrace(); } return file; }
在前台頁面是需要做的就是發送一個鏈接就可以了。
特別注意,
經常忽視的問題,編碼的問題,這里需要統一編碼。
如果出現了word文件不能打開的情況,建議看一下后台文件是否報錯。如果后台沒有報錯的話,建議用editplus打開word的文檔,查看文檔中是否有亂碼的情況。
筆者第一次使用的時候,經常出現word文件不能打開的問題,於是我在editplus中打開,發現部分漢字是亂碼的,加了上圖紅框中的默認編碼的設置之后就可以了。
以上代碼是本人親測過的,可以放心使用。如有不明白的地方,歡迎交流。如有不正確的地方或累贅的地方也可以互相交流。