准备word模板,将里面需要写入的内容以${变量名}形式表现。如图
保存word。另存为xml格式文件。
将model.xml更改后缀名改为model.ftl。这个文件我存在在E盘的根目录。等下需要加载该文件,所以文件路径尽量不要带中文。
代码工作,首先引入依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
代码
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class WpsUtil {
private Configuration configuration = null;
public WpsUtil(){
configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
}
public static void main(String[] args) {
WpsUtil test = new WpsUtil();
test.createWord();
}
public void createWord(){
Map<String,Object> dataMap=new HashMap<String,Object>();
getData(dataMap);
try {
configuration.setDirectoryForTemplateLoading(new File("E:\\")); //扫描路径
} catch (IOException e) {
e.printStackTrace();
}
Template t=null;
try {
t = configuration.getTemplate("model.ftl"); //文件名
} catch (IOException e) {
e.printStackTrace();
}
File outFile = new File("E:\\temp\\"+Math.random()+".doc");
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
t.process(dataMap, out);
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/*
模板文档里对应的字段设置值
*/
private void getData(Map<String, Object> dataMap) {
dataMap.put("activityName", "测试活动");
dataMap.put("sTime", "2012-12-12");
dataMap.put("eTime", "2022-12-12");
dataMap.put("month", "2");
dataMap.put("day", "13");
dataMap.put("activityTotalCash", "1000");
dataMap.put("activityCash", "100");
}
}
测试已成功生成文件