1.Freemarker简介
FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页、电子邮件、配置文件、源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。
2.使用freemark导出doc文档
2.1设置ftl文件模板
新建一个doc文档,内容如下
然后另存为xml文件,如图:
使用文本编辑器打开xml文件,找到占位符 ${username} 和 ${tool} 确保不被xml标签分割,除此之外,还有一个很长的base64编码的字符串文本,这个就是图片,我们把这个文本删掉,使用 ${imgStr} 替换。如图:
最后修改xml后缀名称为ftl
2.2 编码导出doc文档
package com.yuwen;
import sun.misc.BASE64Encoder;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
/**
* className: Domain <br/>
* packageName:com.yuwen <br/>
*
* @author yuwen <br/>
* @date: 2019-11-12 21:50 <br/>
*/
public class Domain {
public static void main(String[] args) throws Exception {
// 模板所在文件夹
File dir = new File(Domain.class.getClassLoader().getResource("").getPath() + "/ftl");
// 图片路径
String imgpPath = Domain.class.getClassLoader().getResource("").getPath() + "img/timg.jpg";
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("username", "玉皇大帝");
dataMap.put("tool", "freemaker");
dataMap.put("imgStr", getImgStr(imgpPath));
ExportDoc.export(dataMap, dir, "新建 Microsoft Word 文档.ftl");
}
/**
* 获取指定文件图片的base64字符串
*
* @param imgPath
* @return
*/
public static String getImgStr(String imgPath) throws Exception {
FileInputStream fileInputStream = new FileInputStream(new File(imgPath));
byte[] b = new byte[fileInputStream.available()];
fileInputStream.read(b);
BASE64Encoder base64Encoder = new BASE64Encoder();
return b.length == 0 ? "" : base64Encoder.encode(b);
}
}
package com.yuwen;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Map;
/**
* className: ExportDoc <br/>
* packageName:java.com.yuwen <br/>
*
* @author yuwen <br/>
* @date: 2019-11-12 21:43 <br/>
*/
public class ExportDoc {
public static void export(Map<String, Object> dataMap, File dir, String fileName) throws Exception {
// 1.新建配置对象,设置版本号,版本号与pom中引入的一致
Configuration configuration = new Configuration(new Version("2.3.28"));
// 2.设置字符集
configuration.setDefaultEncoding("UTF-8");
// 3.设置加载模板的文件夹(.ftl模板文件所在文件夹)
configuration.setDirectoryForTemplateLoading(dir);
// 4.获取模板并且设置字符集
Template template = configuration.getTemplate(fileName, "UTF-8");
// 5.构造目标文件的输出流
File file = new File("D:/" + fileName.substring(0, fileName.lastIndexOf(".")) + ".doc");
Writer writer = new FileWriter(file);
// 6.构建doc文档
template.process(dataMap, writer);
System.out.println("构建完成,文件路径:" + file.getPath());
}
}
以上
案例代码:https://download.youkuaiyun.com/download/Yuwen_forJava/11973398?spm=1001.2014.3001.5503
没积分打赏得留下qq邮箱即可