java導出word(2003版doc格式) FreeMarker+XML實現

FreeMarker+XML實現寫word

最近在接觸對於word的讀寫操作,以前用的是jacob,但是有弊端(配置麻煩+平臺限制),無意間看到了用Freemarker+XML的方式也可以操作word,而且樣式根本不會丟,也不受平臺限制。花了一天時間琢磨出來點東西,今天給大家呈上。

解釋下原理:word從2003版就支持xml格式,而freemarker是java封裝的模板工具,兩者結合也就是在xml中需要動態生成的部分調用freemarker的指令(類似於EL表達式),來生成我們需要的數據,再用流輸出文件,就達到了寫word的效果。

優點: 跨平臺、樣式不會丟失
缺點: 模板製作比較麻煩

ps:這裏只是簡單的演示,具體的需要根據項目需要來完成需求。

下面我爲大家展示一下具體實現方法:

  1.需要自定義一個模板,可以自己新建一個word文件,樣式和假數據填充完成後,另存爲xml格式,修改成模板,如下圖:



2.編寫用freemarker來處理xml的工具類  xmltoword.java 代碼如下:

public class XmlToExcel {
	
	
	private static XmlToExcel tplm = null;
	 private Configuration cfg = null;

	 private XmlToExcel() {
	  cfg = new Configuration();
	 try {
	  //註冊tmlplate的load路徑
	   cfg.setClassForTemplateLoading(this.getClass(), "/template/");
	  } catch (Exception e) {
	   
	  }
	 }

	 private static Template getTemplate(String name) throws IOException {
	  if(tplm == null) {
	   tplm = new XmlToExcel();
	  }
	  return tplm.cfg.getTemplate(name);
	 }
	 
	 /**
	  * 
	  * @param templatefile 模板文件
	  * @param param        需要填充的內容
	  * @param out			填充完成輸出的文件
	  * @throws IOException
	  * @throws TemplateException
	  */
	 public static void process(String templatefile, Map param ,Writer out) throws IOException, TemplateException{
	  //獲取模板
	  Template template=XmlToExcel.getTemplate(templatefile);
	  template.setOutputEncoding("UTF-8");
	  //合併數據
	  template.process(param, out);
	  if(out!=null){
			out.close();
		}
	 }
	public static void main(String[] args) {
		//測試數據
		 Map<String,Object> param = new HashMap<String, Object>();
		  param.put("test","我的測試數據");
		  try {
		Writer out = new OutputStreamWriter(new FileOutputStream(new File("d:\\test.doc")),"UTF-8");				
		XmlToExcel.process("test.xml", param,out);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
	}

}

其實就是調用template的process方法來合併數據,然後freemarker通過writer來輸出文件。

模板所在的路徑:template/test.xml


3.運行完成後出現的結果,如圖:


這裏標題變成了在工具類中定義的map中的數據。

這裏只是生成doc格式的數據 ,下一篇將會介紹如何生成docx格式的word




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