import java.io.BufferedWriter;java import java.io.File;數據庫 import java.io.FileOutputStream;this import java.io.IOException;spa import java.io.OutputStreamWriter;xml import java.io.Writer;utf-8 import java.util.Map;ci import freemarker.template.Configuration;文檔 import freemarker.template.Template;get
public class DocumentHandler {servlet private Configuration configuration = null;
/** * 建立configuration * @param ftlSrc 模版存放路徑,ftl所在的文件夾路徑 */ public DocumentHandler(String ftlSrc) { configuration = new Configuration(); configuration.setDefaultEncoding("utf-8"); try { configuration.setDirectoryForTemplateLoading(new File(ftlSrc)); } catch (IOException e) { e.printStackTrace(); } }
/** * 根據ftl生成word方法 * @param dataMap -- 數據集 * @param fileSrc -- 生成後的文件地址 * @param ftlName -- ftl模版名稱 */ public void createOrderAndDown(Map<String,Object> dataMap,String fileSrc,String ftlName) { Template t=null; try { //test.ftl爲要裝載的模板 t = configuration.getTemplate(ftlName);
} catch (IOException e) { e.printStackTrace(); } //輸出文檔路徑及名稱 File outFile = new File(fileSrc); //若是輸出目標文件夾不存在,則建立 if (!outFile.getParentFile().exists()){ outFile.getParentFile().mkdirs(); } Writer out = null; try { out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8")); //生成 t.process(dataMap, out);
} catch (Exception e) { e.printStackTrace(); }finally { if(out!=null){ //關閉流 try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 要把模版生成合同 * @param dataMap 數據map集合 * @param fileSrc 生成後的文件路徑 */ public void createDoc(Map<String,Object> dataMap,String fileSrc) { //設置模本裝置方法和路徑,FreeMarker支持多種模板裝載方法。能夠重servlet,classpath,數據庫裝載, //這裏咱們的模板是放在/com/zhiwei/credit/util/xmlToWord/firstCreditor包下面 // configuration.setClassForTemplateLoading(this.getClass(), "/com/zhiwei/credit/util/xmlToWord/firstCreditor"); // configuration.setServletContextForTemplateLoading(ServletActionContext.getContext(), "WEB-INF/templates"); // configuration.setDirectoryForTemplateLoading(arg0); Template t=null; try { //test.ftl爲要裝載的模板 t = configuration.getTemplate("firstCreditor.ftl"); } catch (IOException e) { e.printStackTrace(); } //輸出文檔路徑及名稱 File outFile = new File(fileSrc); //若是輸出目標文件夾不存在,則建立 if (!outFile.getParentFile().exists()){ outFile.getParentFile().mkdirs(); } Writer out = null; try { out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8")); //生成 t.process(dataMap, out); } catch (Exception e) { e.printStackTrace(); }finally { if(out!=null){ //關閉流 try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
} |