1、freemarker生成wordjava
1.建立模板。app
我建立模板的方法比较简单,也不知道有没有其余更好的方法,有的话,请告诉我吧~编辑器
首先是新建一个word文档,按照内容格式排好版,而后在须要注入信息的位置先写上占位置的数据,如图1,而后另存为xml文件(我是存为2003版本的xml),ui
而后用文本编辑器把xml打开,在xml中把对应的数据改成freemarker的输出表达式,如图2,而后保存,把xml的后缀名改成freemarker的文件后缀名ftl,即是一个freemarker模板了。this
这个是word中写的数据spa
Name: ${name} Password:${password}
如今转成xml,再换成ftlcode
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <?mso-application progid="Word.Document"?> <w:wordDocument xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml" xmlns:v="urn:schemas-
如今咱们来操做它orm
package com.lianrui.commons.tools; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.HashMap; import java.util.Map; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; public class Freemark { /** * freemark模板配置 */ private static Configuration configuration; public static void main(String[] args){ Freemark freemark = new Freemark("/conf"); //生成word Map<String,Object> map = new HashMap<String, Object>(); map.put("name", "heinrich"); map.put("password", "heinrich"); freemark.createWord("F:/logo/","logo.doc","name.ftl",map); } /** * * @param filePath:保存的文件路径 * @param fileDocName:保存后的文件名称 * @param templateName:freemark模版的名字 * @param map:须要传递的数据 */ public void createWord(String filePath,String fileDocName,String templateName,Map<String,Object> map){ Template t = null; try { //获取模板信息 t = configuration.getTemplate(templateName); } catch (IOException e) { e.printStackTrace(); } File outFile = new File(filePath+fileDocName); Writer out = null; try { out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } try { //输出数据到模板中,生成文件。 t.process(map, out); out.close(); } catch (TemplateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * freemark初始化 * @param templatePath 模板文件位置 */ @SuppressWarnings("deprecation") public Freemark(String templatePath) { configuration = new Configuration(); configuration.setDefaultEncoding("utf-8"); configuration.setClassForTemplateLoading(this.getClass(),templatePath); } }
生成了一个word文档xml
Name: heinrichutf-8
Password:heinrich
是否是很方便