天天看點

使用FreeMaker生成word文檔

依賴

<!-- 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();
        }
    }
}