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(); } } } }