在SSH2项目中兑现使用Freemark导出Word文档
在SSH2项目中实现使用Freemark导出Word文档
最近做OA系统要求导出部门信息的doc文档信息,于是自己用了最简便的方法完成这点。
package com.rocky.oa.util; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; import com.rocky.oa.entity.DepartInfo; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; public class CreatWordUtil { @SuppressWarnings() //String dir(ftl模板文件的位置),String toDir(导出doc放置的位置) public static void creatWordDepartInfo(String dir,String toDir,DepartInfo departInfo) { try { //创建配置实例 Configuration cfg = new Configuration(); cfg.setDefaultEncoding("utf-8"); cfg.setDirectoryForTemplateLoading(new File(dir)); //模板所在的文件夹 cfg.setObjectWrapper(new DefaultObjectWrapper()); //获取模板 /** * 生成模板 * 1、officeWord另存为生成一个xml文件 * 2、把xml改为ftl * 3,把xml编码格式改为GBK * 4,使用${str}代替字符串 * 如果生成的word格式为ANSI,则将ftl模板第一行声明编码改为gbk * */ Template temp = cfg.getTemplate(departinfo.ftl,UTF-8); temp.setEncoding("utf-8"); //创建数据模型 Map root = new HashMap(); root.put(departname", departInfo.getDepartName()); root.put(branchname",departInfo.getBranchInfo().getBranchName() ); root.put(departInfo.getUserInfo().getUserName()); root.put(departInfo.getConnectTelNo().toString()); root.put(departInfo.getConnectMobileTelNo().toString()); root.put(departInfo.getFaxes().toString()); //将模板和数据模型合并生成文件 File docFile = new File(toDir); Writer docout = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile))); temp.process(root, docout); } catch (Exception e) { e.printStackTrace(); } } } public String report() { DepartInfo departInfo = departService.get(id); String path = ServletActionContext.getServletContext().getRealPath( "/resource"); File file = new File("c://部门信息"); if (!file.exists()) { file.mkdirs(); } String newPath = "c://部门信息/" + departInfo.getDepartName() + ".doc"; CreatWordUtil.creatWordDepartInfo(path, newPath, departInfo); return "relist"; }