在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";
	}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值