利用freemarker技術,填充word模板

1.另存word爲xml格式文件

wKiom1L6AE_hbA-9AAD4cVVr5Pk047.jpg

2.修改對應內容標記

wKioL1L6AGGyU96HAAFE21jLYdo302.jpg


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

wKiom1L6ATDyViTjAACXZA4hVzg078.jpg

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章