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.結果