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
是否是很方便