使用FreeMarker導出Word

Step1:

新建一個WordExport   java項目,加入freemarker.jar.



Step2:

將要導出的Word模板轉化爲xml.

打開模板,單擊‘文件’,單擊’另存爲‘



Step3:將xml模板中要插入數據的地方加上freemarker語句(轉化前可以先在要插入的地方填寫標示,通過查找標記來查找模板要插入的地方)(可用XMLSpy先將xml模板格式化)。


如果要插入只是一個字符串(如createDate),則在要插入處加上

<#if createDate??>${createDate!""}<#else> </#if>
如果要插入的是Map中的屬性值(如clazz.school),則在要插入處加上

<#if clazz??>${clazz.school!""}<#else> </#if>
    如果要插入是List,則在要插入處加上


<#if students??>
			<#list students as student><!-- 將每一個元素命名爲student-->
...
<w:t>${student.name!""}</w:t>
...
</#list>
 </#if>	


Step4:編寫java類:

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 freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class Export {
	public static   void  docOut() {
        Configuration cfg = new Configuration();

        cfg.setDefaultEncoding("utf-8");
        
        try {
			Template temp =  cfg.getTemplate("test.xml");
			
			temp.setEncoding("UTF-8");
			
			//data爲要導出的數據
			Map<String,Object> data = new HashMap<String, Object>();
			
			
			Map<String,Object> clazz = new HashMap<String,Object>();
			clazz.put("school", "重理工");
			clazz.put("clazzName", "軟件一班");
			clazz.put("clazzTea", "不便告知");
			data.put("clazz", clazz);
			
			List<Map<String, Object>> students = new ArrayList<Map<String, Object>>();
			Map<String, Object> s1 = new HashMap<String, Object>();
			s1.put("name", "bin");
			s1.put("sex", "男");
			s1.put("age",22);
			students.add(s1);
			
			HashMap<String, Object> s2 = new HashMap<String, Object>();
			s2.put("name", "yu");
			s2.put("sex", "女");
			s2.put("age", 20);
			students.add(s2);
			
			data.put("students",students);
			
			data.put("createDate", "2012年");
			
			//一定要設置輸出流的編碼,否則會出錯
			Writer docout = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("test1.doc")),"UTF-8"));
			docout.close();
			//導出
			temp.process(data, docout);
		} 
        catch(TemplateException e){
        	e.printStackTrace();
        }
        catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	
	public static void main(String[] args) {
		docOut();
	}

}

Step4:導出結果爲:


下面是程序實例下載地址

http://download.csdn.net/detail/q1w2e3a_4s5d6z/6379685

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章