1.另存word为xml格式文件
2.修改对应内容标记
3.构建配置类
import java.io.File;
import java.io.IOException;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
public class MyFreeMarker {
private static Configuration config = null;
private MyFreeMarker(){
}
public static Configuration getConfiguration(){
if(config == null){
config = new Configuration();
}
try {
// 设置模版的根目录
config.setDirectoryForTemplateLoading(new File("D://templates"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 指定模版数据模型
config.setObjectWrapper(new DefaultObjectWrapper());
return config;
}
}
4.完成数据填充,并输出文件
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class WordUtil {
public static void main(String[] args) throws Exception {
WordUtil w = new WordUtil();
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("name", "郝杰");
map.put("dept", "UEC");
String srcPath = "流程手册.xml";
String desPath = "d://out.doc";
w.createWord(map, srcPath, desPath);
}
public void createWord(HashMap<String, Object> map, String srcPath, String desPath) throws Exception{
Configuration config = MyFreeMarker.getConfiguration();
Template template = config.getTemplate(srcPath);
File outfile = new File(desPath);
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfile), "utf-8"));
template.process(map, out);
out.flush();
}
}
5.结果
转载于:https://blog.51cto.com/haojie4jdk/1358190