Java用freemarker匯出word實用樣本_java

來源:互聯網
上載者:User

最近一個項目要匯出word文檔,折騰老半天,發現還是用freemarker的模板來搞比較方便省事,現總結一下關鍵步驟,供大家參考,這裡是一個簡單的試卷產生例子。

一、模板的製作

先用Word做一個模板,如下圖:
(注意,上面是有表格的,我設定了邊框不可見)然後另存新檔XML檔案,之後用工具開啟這個xml檔案,有人用firstobject XML Editor感覺還不如notepad++,我這裡用notepad++,主要是有高亮顯示,和元素自動配對,效果如下:
上面黑色的地方基本是我們之後要替換的地方,比如xytitle替換為${xytitle},對已表格要十分注意,比如選擇題下面的表格,我們可以通過<w:tr>尋找來定位,一對<w:tr></w:tr>代表一行,也就是一條記錄(一道題),我們這裡要用一對<#list></#list>來將其包括,以便後續填充資料,具體可參照Freemarker頁面文法,例如這裡選擇題,我們是兩行為一條記錄,所以要<#list></#list>要包括兩行,形如:<#list table1 as plan1><w:tr>題號 題目</w:tr><w:tr>選項</w:tr></#list>,然後在這其中找著對應的xzn,xztest,ans1,ans2,ans3,ans4替換為${plan1.xzn},${plan1.xztest},${plan1.ans1},${plan1.ans2},${plan1.ans3},${plan1.ans4},注意這裡的table1及plan1命名,table1後續填充資料要用到,其他的替換同理操作,得到效果如下:
儲存後,修改尾碼名為ftl,至此模板製作完畢。

二、編程實現

這裡用到了freemarker-2.3.13.jar包,代碼如下:

package common;  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.Map;  import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException;  public class DocumentHandler {   private Configuration configuration = null;   public DocumentHandler() {   configuration = new Configuration();   configuration.setDefaultEncoding("utf-8");  }   public void createDoc(Map<String,Object> dataMap,String fileName) throws UnsupportedEncodingException {   //dataMap 要填入模本的資料檔案   //設定模本裝置方法和路徑,FreeMarker支援多種模板裝載方法。可以重servlet,classpath,資料庫裝載,   //這裡我們的模板是放在template包下面   configuration.setClassForTemplateLoading(this.getClass(), "/template");   Template t=null;   try {    //test.ftl為要裝載的模板    t = configuration.getTemplate("fctestpaper.ftl");   } catch (IOException e) {    e.printStackTrace();   }   //輸出文檔路徑及名稱   File outFile = new File(fileName);   Writer out = null;   FileOutputStream fos=null;   try {    fos = new FileOutputStream(outFile);    OutputStreamWriter oWriter = new OutputStreamWriter(fos,"UTF-8");    //這個地方對流的編碼不可或缺,使用main()單獨調用時,應該可以,但是如果是web請求匯出時匯出後word文檔就會打不開,並且包XML檔案錯誤。主要是編碼格式不正確,無法解析。    //out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));     out = new BufferedWriter(oWriter);   } catch (FileNotFoundException e1) {    e1.printStackTrace();   }      try {    t.process(dataMap, out);    out.close();    fos.close();   } catch (TemplateException e) {    e.printStackTrace();   } catch (IOException e) {    e.printStackTrace();   }      //System.out.println("---------------------------");  } } 

然後是準備資料調用就行,代碼如下:

package com.havenliu.document;  import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;  public class Main {   /**   * @param args   * @throws UnsupportedEncodingException   */  public static void main(String[] args) throws UnsupportedEncodingException {;    Map<String, Object> dataMap = new HashMap<String, Object>();   dataMap.put("xytitle", "試卷");   int index = 1;   // 選擇題   List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();//題目   List<Map<String, Object>> list11 = new ArrayList<Map<String, Object>>();//答案   index = 1;   for (int i = 0; i < 5; i++) {     Map<String, Object> map = new HashMap<String, Object>();    map.put("xzn", index + ".");    map.put("xztest",      "( )作業系統允許在一台主機上同時串連多台終端,多個使用者可以通過各自的終端同時互動地使用電腦。");    map.put("ans1", "A" + index);    map.put("ans2", "B" + index);    map.put("ans3", "C" + index);    map.put("ans4", "D" + index);    list1.add(map);     Map<String, Object> map1 = new HashMap<String, Object>();    map1.put("fuck", index + ".");    map1.put("abc", "A" + index);    list11.add(map1);     index++;   }   dataMap.put("table1", list1);   dataMap.put("table11", list11);    // 填空題   List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();   List<Map<String, Object>> list12 = new ArrayList<Map<String, Object>>();   index = 1;   for (int i = 0; i < 5; i++) {     Map<String, Object> map = new HashMap<String, Object>();    map.put("tkn", index + ".");    map.put("tktest",      "作業系統是電腦系統中的一個___系統軟體_______,它管理和控制電腦系統中的___資源_________.");    list2.add(map);     Map<String, Object> map1 = new HashMap<String, Object>();    map1.put("fill", index + ".");    map1.put("def", "中級調度" + index);    list12.add(map1);     index++;   }   dataMap.put("table2", list2);   dataMap.put("table12", list12);    // 判斷題   List<Map<String, Object>> list3 = new ArrayList<Map<String, Object>>();   List<Map<String, Object>> list13 = new ArrayList<Map<String, Object>>();   index = 1;   for (int i = 0; i < 5; i++) {     Map<String, Object> map = new HashMap<String, Object>();    map.put("pdn", index + ".");    map.put("pdtest",      "複合型防火牆防火牆是內部網與外部網的隔離點,起著監視和隔絕應用程式層通訊流的作用,同時也常結合過濾器的功能。");    list3.add(map);     Map<String, Object> map1 = new HashMap<String, Object>();    map1.put("judge", index + ".");    map1.put("hij", "對" + index);    list13.add(map1);     index++;   }   dataMap.put("table3", list3);   dataMap.put("table13", list13);    // 簡答題   List<Map<String, Object>> list4 = new ArrayList<Map<String, Object>>();   List<Map<String, Object>> list14 = new ArrayList<Map<String, Object>>();   index = 1;   for (int i = 0; i < 5; i++) {     Map<String, Object> map = new HashMap<String, Object>();    map.put("jdn", index + ".");    map.put("jdtest", "說明作業調度,中級調度和進程調度的區別,並分析下述問題應由哪一級發送器負責。");    list4.add(map);     Map<String, Object> map1 = new HashMap<String, Object>();    map1.put("answer", index + ".");    map1.put("xyz", "說明作業調度,中級調度和進程調度的區別,並分析下述問題應由哪一級發送器負責。");    list14.add(map1);     index++;   }   dataMap.put("table4", list4);   dataMap.put("table14", list14);    MDoc mdoc = new MDoc();   mdoc.createDoc(dataMap, "E:/outFile.doc");  }  } 

注意上面map中的key必須和模板中的對應,否則會報錯。效果如下:

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.