1.編輯好word
2.將word模板另存為xml格式, 把需要動態生成的文字用${xxx}代替
eg: 張強 替換為:${name}
注意:圖片是很長的一個base64的字符,同樣替換就好 比如替換為 ${photo}
3.將xml模板文件后綴名改為.ftl (這點其實可以不要,我看網上好多命名為 .ftl 還有 .tpl, 開始也糾結看了很久,經實踐,后綴名,改不改都無所謂,改成 .ttt也行,猜測只是為了著名使用freeMark 解析的所以才命名為 .ftl, 另外猜測文件頭已經說明是下,xml了,所以你改成任何后綴名都可以,反正都是xml文件)
4.如果有循環輸出 搜索關鍵字,補入 <#list userList as user> </#list>或其它freemarker標簽
相關代碼片段
需要生成的數據:
//獲得圖片的base64碼 public static String getImageBase(String src) throws Exception { if (src == null || src == "") { return ""; } File file = new File(src); if (!file.exists()) { return ""; } InputStream in = null; byte[] data = null; try { in = new FileInputStream(file); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data); }
/** * 生成doc文件 * @param filePath 臨時文件路徑 * @param templateName 模板名字 * @param dataMap 數據集合 * @return */ public static File createDoc(String filePath, String templateName, Map<String,Object> dataMap){ // 獲取模板 Configuration configuration = new Configuration(); configuration.setDefaultEncoding("utf-8"); configuration.setClassForTemplateLoading(FileUtil.class, "/tpl"); Template t = null; File file = new File(filePath); try { file.createNewFile(); t = configuration.getTemplate(templateName); t.setEncoding("UTF-8"); Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath),"UTF-8")); t.process(dataMap, out); out.close(); } catch (IOException e) { log.error("根據xml模板用freeMarker生成word文檔IO異常", e); } catch (TemplateException e) { log.error("根據xml模板用freeMarker生成word文檔模板異常", e); } return file; }
/** * 下載文件到瀏覽器 * @param request * @param response * @param filename 要下載的文件名 * @param file 需要下載的文件對象 * @throws IOException */ public static void downFile(HttpServletRequest request, HttpServletResponse response, String filename, File file) throws IOException { // 文件存在才下載 if (file.exists()) { OutputStream out = null; FileInputStream in = null; try { // 1.讀取要下載的內容 in = new FileInputStream(file); // 2. 告訴瀏覽器下載的方式以及一些設置 // 解決文件名亂碼問題,獲取瀏覽器類型,轉換對應文件名編碼格式,IE要求文件名必須是utf-8, firefo要求是iso-8859-1編碼 String agent = request.getHeader("user-agent"); if (agent.contains("FireFox")) { filename = new String(filename.getBytes("UTF-8"), "iso-8859-1"); } else { filename = URLEncoder.encode(filename, "UTF-8"); } // 設置下載文件的mineType,告訴瀏覽器下載文件類型 String mineType = request.getServletContext().getMimeType(filename); response.setContentType(mineType); // 設置一個響應頭,無論是否被瀏覽器解析,都下載 response.setHeader("Content-disposition", "attachment; filename=" + filename); // 將要下載的文件內容通過輸出流寫到瀏覽器 out = response.getOutputStream(); int len = 0; byte[] buffer = new byte[1024]; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } } }