1. pom文件中引入FreeMarker依赖
<!-- freemarker jar -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.20</version>
</dependency>
2. 使用word 创建模板文档如图
3. 将word文档另存为xml格式,同时将变量修改为${variable}格式
4.将xml文件后缀名改为ftl格式
5.将ftl文件放在/templates/目录下
6.代码实现:
工具类:
package com.example.demo.common;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import org.springframework.util.ResourceUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
public class CreateWordUtil {
public static void createWord(Map dataMap){
try {
//Configuration 用于读取ftl文件
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
//获取根目录
File path = new File(ResourceUtils.getURL("classpath:").getPath());
if(!path.exists()) path = new File("");
System.out.println("path:"+path.getAbsolutePath());
//如果上传目录为/templates/,则可以如下获取:
File upload = new File(path.getAbsolutePath(),"templates/");
if(!upload.exists()) upload.mkdirs();
System.out.println("upload url:"+upload.getAbsolutePath());
//指定路径的第一种方式,
//configuration.setClassForTemplateLoading();
//指定路径的第二种方式,具体路径
configuration.setDirectoryForTemplateLoading(upload);
//输出文档路径及名称
File outFile = new File("D:/报销信息导出.doc");
//以utf-8的编码读取ftl文件
Template template = configuration.getTemplate("puser.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();
}
}
}
测试类
package com.example.demo.controller;
import com.example.demo.common.CreateWordUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/demo")
public class DemoController {
@GetMapping("/test")
public void test() {
Map<String, Object> dataMap = new HashMap<String, Object>();
///姓名
dataMap.put("name", "张三");
//年龄
dataMap.put("age", 15);
//地址
dataMap.put("address","山西省");
//其他
dataMap.put("other","其他");
CreateWordUtil.createWord(dataMap);
}
}
测试结果:
D盘目录下正常生成文件。内容如下: