java使用freemarker自定义doc

通过使用freemarker的doc模板将数据转成doc

核心工具类

package com.home.mail.mail.utils;



import com.home.mail.mail.entity.MailMessage;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class DocUtil {

    public static void toDoc(MailMessage mailMessage){
        Map<String,Object> dataMap = new HashMap<String, Object>();
        try {
            //项目
            dataMap.put("project1", mailMessage.getProject1());
            dataMap.put("project2", mailMessage.getProject2());
            dataMap.put("project3", mailMessage.getProject3());
           //日期
            dataMap.put("timeperiod", mailMessage.getTimeperiod());
            //计划,工作内容
            dataMap.put("zhou1", mailMessage.getZhou1());
            dataMap.put("zhou2", mailMessage.getZhou2());
            dataMap.put("zhou3", mailMessage.getZhou3());
            dataMap.put("zhou4", mailMessage.getZhou4());
            dataMap.put("zhou5", mailMessage.getZhou5());
            dataMap.put("zhou6", mailMessage.getZhou6());
            dataMap.put("zhou7", mailMessage.getZhou7());

            //Configuration 用于读取ftl文件
            Configuration configuration = new Configuration(new Version("2.3.8"));
            configuration.setDefaultEncoding("utf-8");

            /**
             * 以下是两种指定ftl文件所在目录路径的方式,注意这两种方式都是
             * 指定ftl文件所在目录的路径,而不是ftl文件的路径
             */
            //指定路径的第一种方式(根据某个类的相对路径指定)
//                configuration.setClassForTemplateLoading(this.getClass(), "");

            //指定路径的第二种方式,我的路径是C:/a.ftl
            configuration.setDirectoryForTemplateLoading(new File("E:/worklog/"));

            //输出文档路径及名称
            File outFile = new File("E:/worklog/"+mailMessage.getFilename()+".doc");
            //此处是我发送邮件用的
            //ContextThread.FileUrl = "E:/worklog/"+mailMessage.getFilename()+".doc";
            //以utf-8的编码读取ftl文件
            Template template = configuration.getTemplate("work.ftl", "utf-8");
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
            template.process(dataMap, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        //toDoc();
    }
}

 

创建ftl模板

将你所需要填入数据的地方用${key}代替,key就是工具类中map的key。

 

如何获取ftl模板呢。

就是把doc另存为xml,然后改名为.ftl。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值