freemark生成word

第一步,制作ftl模板
先用word编辑好文档,另存为.xml文件(这里需要注意,存为 2003xml 文件,要不以后生成的word可能会出现office打不开的情况),最后重名为.ftl文件即可。
在这里插入图片描述
使用变量替换掉需要动态更新的内容,我这里是图片
在这里插入图片描述
第二步,java代码生成报告

 public void createReportDoc(String lineBase64) {//图片base64位编码
        Map<String, Object> map = new HashMap<>();
        map.put("img_line", lineBase64);
        String fileName = System.currentTimeMillis() + ".doc";
        try {
            docHelper.createWord(map, "report.ftl", "E:/temp/report", fileName);
            logger.info("生成{}成功", fileName);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("生成实时分析报告失败");
            throw new BusinessException("生成实时分析报告失败");
        }
    }


import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.stereotype.Component;

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


@Component
public class DocHelper {
    public void createWord(Map dataMap,String templateName,String filePath,String fileName) throws Exception{
        //创建配置实例
        Configuration configuration = new Configuration();

        //设置编码
        configuration.setDefaultEncoding("UTF-8");

        configuration.setClassForTemplateLoading(DocHelper.class,"/template");

        //获取模板
        Template template = configuration.getTemplate(templateName);

        //输出文件
        File outFile = new File(filePath+File.separator+fileName);

        //如果输出目标文件夹不存在,则创建
        if (!outFile.getParentFile().exists()){
            outFile.getParentFile().mkdirs();
        }

        //将模板和数据模型合并生成文件
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));


        //生成文件
        template.process(dataMap, out);

        //关闭流
        out.flush();
        out.close();
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值