用Freemarker導出word文檔

一、 用word寫一個須要導出的模板,將須要動態修改的內容替換成***。若是須要在word中添加圖片,須要加入一張圖片佔位,而後另存爲xml格式,後綴名修改成.ftl。
注意:(1)編寫模板時應使用Microsoft Office Word 2003,以免出現導出的word文檔不能用Word 2003打開的問題。
(2)同時要注意word格式問題。若是在word導出成功以後發現格式不協調等問題,就只能重新來過了。
(3)加入圖片佔位時,請儘可能選擇小於50K的圖片,而且把圖片的大小和位置調整好。選擇小圖片的緣由是避免xml文件過大致使打開時緩慢甚至卡死。
二、 用Firstobject free XML editor打開ftl文件,選擇Tools下的Indent【或者按快捷鍵F8】格式化文件內容。左邊是ftl的文檔結構,右邊是文檔內容。
注意:若是想讓格式化以後的代碼更清晰,須要在在tool->preferences裏設置Indent爲Tabs。
三、 將ftl中須要動態修改內容的地方,換成freemarker的標識。其實就是Map<String, Object>中key,如${year}。
四、 在加入了圖片佔位的地方,會看到以下的一片base64編碼後的代碼:
<w:binData w:name="wordml://03000001.png" xml:space="preserve">${grade.photo}</w:binData>
只要將base64的代碼替換成例如:${image},以下:
<w:binData w:name="wordml://03000001.png" xml:space="preserve">${grade.photo}</w:binData>
注意:「>${grade.photo}<」這尖括號中間不能加任何其餘的諸如空格,tab,換行等符號。
若是須要循環,則使用:
  <#list grade.list as student>...</#list>,
具體請看Demo。
五、 標識替換完以後,模板就弄完了。
特別注意:必定不要用word打開ftl模板文件,不然xml內容會發生變化,致使前面的工做白作了。
 
處理代碼以下:

/**
      * @注意dataMap裏存放的數據Key值要與模板中的參數相對應
      */
     public void create(Map<String, Object> dataMap) throws Exception {
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        // 模板放在com.canyou.template包下面,經過classpath裝載
        configuration.setClassForTemplateLoading(this.getClass(),
               "/com/canyou/template");
        Template t = configuration.getTemplate("test.ftl");// 設置要裝載的模板
        File outFile = new File(docPath);
        if (!outFile.exists()) {
            outFile.createNewFile();
        }
        Writer out = new BufferedWriter(new OutputStreamWriter(
               new FileOutputStream(outFile), "utf-8"));
        t.process(dataMap, out);
     }

調用的代碼: java

public static void main(String[] args) { Map<String, Object> dataMap = new HashMap<String, Object>();// 要填入模本的數據文件 Grade grade = new Grade(); grade.setSchool("殘友大學"); grade.setMajor("軟件工程專業"); grade.setYear(2011); grade.setAdviser("夏明"); grade.setNo("0102"); grade.setPhoto(getFileStream("D:\\照片\\http_imgload.jpg")); List<Student> list = new ArrayList<Student>(); for (int i = 0; i < 100; i++) { Student stu = new Student(); stu.setNo("0102" + i); stu.setName("test" + i); stu.setSex(i % 2 == 1 ? "男" : "女"); stu.setAge(20 + i % 5); stu.setAddress("廣東省深圳市福田區雨田路1號"); list.add(stu); }

附:Firstobject free XML editor下載地址:http://www.firstobject.com/dn_editor.htm this

     freemarker 官網:http://freemarker.org/ 編碼

相關文章
相關標籤/搜索