主要程序代碼:
- package com.havenliu.document;
- 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.Writer;
- import Java.util.ArrayList;
- import Java.util.HashMap;
- import Java.util.List;
- 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 dataMap=new HashMap();
- getData(dataMap);
- //設置模本裝置方法和路徑,FreeMarker支持多種模板裝載方法。可以重servlet,classpath,數據庫裝載,
- //這裡我們的模板是放在com.havenliu.document.template包下面
- configuration.setClassForTemplateLoading(this.getClass(), "/com/havenliu/document/template");
- Template t=null;
- try {
- //test.ftl為要裝載的模板
- t = configuration.getTemplate("test.ftl");
- } catch (IOException e) {
- e.printStackTrace();
- }
- //輸出文檔路徑及名稱
- File outFile = new File("D:/temp/outFile.doc");
- Writer out = null;
- try {
- out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
- } catch (FileNotFoundException e1) {
- e1.printStackTrace();
- }
- try {
- t.process(dataMap, out);
- } catch (TemplateException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * 注意dataMap裡存放的數據Key值要與模板中的參數相對應
- * @param dataMap
- */
- private void getData(Map dataMap)
- {
- dataMap.put("author", "張三");
- dataMap.put("remark", "這是測試備注信息");
- List
- _table1=new ArrayList();
- Table1 t1=new Table1();
- t1.setDate("2010-10-1");
- t1.setText("制定10月開發計劃內容。");
- _table1.add(t1);
- Table1 t2=new Table1();
- t2.setDate("2010-10-2");
- t2.setText("開會討論開發計劃");
- _table1.add(t2);
- dataMap.put("table1", _table1);
- List
- _table2=new ArrayList();
- for(int i=0;i<5;i++)
- {
- Table2 _t2=new Table2();
- _t2.setDetail("測試開發計劃"+i);
- _t2.setPerson("張三——"+i);
- _t2.setBegindate("2010-10-1");
- _t2.setFinishdate("2010-10-31");
- _t2.setRemark("備注信息");
- _table2.add(_t2);
- }
- dataMap.put("table2", _table2);
- }
- }