今天我们来使用freemarker生成word文档
1.首先引入pom文件
我这里使用的2.3.28版本的
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
2. 准备一个模板文件
右击另存为xml格式
3. 生成模板的工具类
import freemarker.template.Configuration;
import freemarker.template.Template;
import tdh.web.log.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import java.io.*;
import java.util.Map;
/**
* 导出word
* @author zhongcg
* @date 2020-06-29
*/
public class FreemarkerToWord {
private static Configuration configuration = null;
static {
try {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
//根据实际需求设置模板目录
configuration.setDirectoryForTemplateLoading(new File("C:\\Users\\DELL\\Desktop"));
} catch (Exception e) {
Logger.error(e.getMessage(), e);
}
}
/**
* @Description:导出word
* @param map 就是值
* @param path 是导出文件路径
* @param ftlFile 是你要使用的模板名
*/
public static void exportWord(Map<String, Object> map, String path, String ftlFile) {
InputStream fin = null;
ServletOutputStream out = null;
try {
Template freemarkerTemplate = configuration.getTemplate(ftlFile);
createDocFile(map,path,freemarkerTemplate);
}catch (Exception e){
Logger.error(e.getMessage(), e);
}finally {
try {
if(fin != null) fin.close();
} catch (IOException e) {
Logger.error(e.getMessage(), e);
}
try {
if(out != null) out.close();
} catch (IOException e) {
Logger.error(e.getMessage(), e);
}
}
}
/**
* @Description:创建doc文件
* @param dataMap 数据
* @param path 生成文件路径
* @param template template
* @return file
*/
private static File createDocFile(Map<?, ?> dataMap, String path, Template template) {
File file = new File(path);
try {
Writer writer = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
template.process(dataMap, writer);
writer.close();
} catch (Exception e) {
Logger.error(e.getMessage(), e);
}
return file;
}
}
4.测试生成
public class Demo {
public static void main(String[] args) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("title", "使用FREEMAKER模板导出word文件");
map.put("name", "张三");
map.put("sex", "男");
map.put("age", "23");
List<String> list = new ArrayList<String>();
list.add("阿里巴巴");
list.add("字节跳动");
list.add("百度");
map.put("experience", list);
FreemarkerToWord.exportWord(map, "C:\\Users\\DELL\\Desktop\\demo.doc", "测试.xml");
}
}
简单的word就这样生成出来了,这里的工作经历我们使用的list,在xml需要这样写
<#list experience as exp>
${exp}
</#list>
这里格式没有事先写好,所以有些难看,另外freemaker也支持替换图片,不过这里需要将图片转换为base64编码,比较麻烦,这里就不在阐述,有兴趣的同学可以自己研究一下。
5.Freemarker提供了3种加载模板目录的方法
1.基于文件系统,我们所使用的就是这种方式
configuration.setDirectoryForTemplateLoading(new File("c:\\"))
2.基于类路径
configuration.setClassForTemplateLoading(this.getClass(), "/");
3.基于Servlet Context
HttpServletRequest request = ServletActionContext.getRequest();
configuration.setServletContextForTemplateLoading(request.getSession().getServletContext(), "/template");
这种方式是指webapps下面的文件夹。
参考:
https://blog.csdn.net/gtlishujie/article/details/52300381