依赖
<!-- freemarker jar -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.20</version>
</dependency>
生成模版文件
- 制作word模版文件,需要填写值的地方用变量名代替;
- 保存为model.xml格式;
- 记事本打开model.xml文件,将所有的变量名替换为${变量名};(需一次完成,否则修改完成之后再次word打开编辑保存,${变量名}会被识别为字符需要重新替换)
- 将model.xml修改后缀名为model.ftl
代码
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
* @Author: Yilia
* @Date: 2020/11/12/0012 10:40
*/
public class DocUtil {
private Configuration configuration = null;
public DocUtil(){
configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
}
public static void main(String[] args) {
DocUtil test = new DocUtil();
test.createWord();
}
public void createWord(){
// 变量名与写入值的键值对
// 变量名可以多但是不能少
Map<String,Object> dataMap=new HashMap<String,Object>();
dataMap.put("acceptanceDate", "1970-01-19 05:54:18");
dataMap.put("repairOrderingMethod", "1");
dataMap.put("responsiblePersonSign", "1");
//模板文件所在路径
configuration.setClassForTemplateLoading(this.getClass(), "/");
Template template = null;
try {
//获取模板文件
template = configuration.getTemplate("repairOfArchives.ftl");
} catch (IOException e) {
e.printStackTrace();
}
//导出文件
File outFile = new File("C:\\Users\\admin\\Desktop\\repair.doc");
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
//将填充数据填入模板文件并输出到目标文件
template.process(dataMap, out);
out.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}