第一步,制作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("生成实时分析报告失败");
}
}
package com.bbd.higgs.credit.helper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.stereotype.Component;
import java.io.*;
import java.util.Map;
/**
* freemark生成word
* Created by wish on 2017/12/11.
*/
@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();
}
}