freemarkを利用してword文書を構築する


本文はfreemarkerを利用してword文書を作成する。基本的な考え方は、wordテンプレートを編集し、テンプレートを03版のxmlファイルに保存し、xmlファイルでfreemakerタグを編集し、動的に出力するデータを構築し、一つのmapに保存し、freemaker.template.Templatess.process(Object jrootMap,Writer out)メソッドを呼び出して、構築したファイルを指定されたストリームに出力することです。         ヒント:wordテンプレートを編集する時に、動的出力が必要なところにfreemarkerタグを書いてください。このように、別のファイルに保存されているxmlファイルの中から編集したいところを見つけやすくなります。wordで生成されたxmlは長くて複雑です。注意xmlファイルのfreemarkerタグの正しさを確認すると、{}にwordタグを添付して削除します。         xmlにループが必要な場所または他のダイナミック処理が必要なところを見つけ、freemarkerのFTLコマンドを書き込み、対応する動的出力を実行します。次は私が書いた列です。データベーステーブル構造をwordファイルに動的に出力します。

import java.io.BufferedWriter;
import java.io.File;
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 freemark.entity.Column;
import freemark.entity.Table;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

public class DocumentHandler {
	private Configuration configuration = null;
	private Map<Object, Object> dataMap = null;

	public DocumentHandler() {
		configuration = new Configuration();
		configuration.setDefaultEncoding("UTF-8");
	}

	public void createDoc(String templateDir, String templateFileName,
			String savePath) {
		//            ,FreeMarker          。   servlet,classpath,     ,
		Template t = null;
		try {
			//        freemarker    
			configuration.setDirectoryForTemplateLoading(new File(templateDir));
			//        
			configuration.setObjectWrapper(new DefaultObjectWrapper());
			//        
			configuration
					.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
			//   Template  
			t = configuration.getTemplate(templateFileName);
		} catch (IOException e) {
			e.printStackTrace();
		}
		//          
		File outFile = new File(savePath);
		Writer out = null;
		try {
			out = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(outFile), "UTF-8"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		try {
			t.process(dataMap, out);
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	//    
	private Map<Object, Object> getData() {
		Map<Object, Object> map = new HashMap<Object, Object>();
		List<Table> tables = new ArrayList<Table>();
		Table table = new Table();
		table.setTableName("tableName");
		Column column = new Column();
		column.setName("ID");
		column.setType("varchar(50)");
		column.setIsRequired("Yes");
		column.setDesc("  ");
		table.getColumns().add(column);
		tables.add(table);
		Table table1 = new Table();
		table1.setTableName("tableName");
		Column column1 = new Column();
		column1.setName("ID");
		column1.setType("varchar(50)");
		column1.setIsRequired("Yes");
		column1.setDesc("  ");
		table1.getColumns().add(column1);
		tables.add(table1);
		map.put("tables", tables);
		return map;
	}

	public Map<Object, Object> getDataMap() {
		return dataMap;
	}
	
	public void setDataMap(Map<Object, Object> dataMap) {
		this.dataMap = dataMap;
	}

	public static void main(String[] args) {
		DocumentHandler dh = new DocumentHandler();
		dh.setDataMap(dh.getData());
		dh.createDoc("d:/test", "test.xml", "d:\\test\\outFile.doc");
	}

}
テンプレートのxmlファイルのキー内容は以下の通りです。

<#list tables as table>
  ...
  <#list table.columns as column>
     ...
  </#list>
  ...
</#list>