1、原料
開源jar包freemarker、eclipse、一份模板word文檔
2、首先設計模板word文檔
一般,通過程序輸出的word文檔的格式是固定的,例如建立一個表格,將表格的標題寫好,表格的內容使用不同的標記標好,設計好word后,將word文檔另存為xml文件(注:只有word2003 以上的版本可以),使用xml工具打開文件,將要輸出到word的內容使用${XX}替換,保存后將文件直接改為tdl后綴
3、使用eclipse編寫程序
1)獲得一個Configuration實例,並為他設置字符集
configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
2)解析出word模板
//獲得類解析器,解析地址templatePath,該地址存放模板 我將模板放在該類的包下即/com/welv/this
configuration.setClassForTemplateLoading(this.getClass(), templatePath);
Template t = configuration.getTemplate(templateName);
t.setEncoding("UTF-8");
3) 將內容輸出到word,並生成文件
Write out = new OutputStreamWrite(new FileOutputStream("輸出的地址"),"utf-8");
//dataMap為map容器用於存放<輸出到word的地點,輸出內容>
t.process(dataMap, out);
out.close();