1. 程式人生 > >使用freemarker模板生成word文件

使用freemarker模板生成word文件

專案中最近用到這個東西,做下記錄。

如下圖,先準備好一個(office2003)word文件當做模板。文件中圖片、姓名、性別和生日已經使用佔位符代替,生成過程中將會根據實際情況進行替換。

然後將word文件另存為“Word XML文件”

使用xml編輯器開啟test.xml,將下圖中的BASE64字串替換為${image},後面程式中將使用這個替換圖片。

完成後,將test.xml重新命名為test.ftl。

接下來,實現程式碼如下:

複製程式碼

public class ExportDoc {
    
    private Configuration configuration;
    private String encoding;
    
    public ExportDoc(String encoding) {
        this.encoding = encoding;
        configuration = new Configuration(Configuration.VERSION_2_3_22);
        configuration.setDefaultEncoding(encoding);
        configuration.setClassForTemplateLoading(this.getClass(), "/com/lichmama/test/templates");
    }
    
    public Template getTemplate(String name) throws Exception {
        return configuration.getTemplate(name);
    }
    
    public String getImageStr(String image) throws IOException {
        InputStream is = new FileInputStream(image);
        BASE64Encoder encoder = new BASE64Encoder();
        byte[] data = new byte[is.available()];
        is.read(data); is.close();
        return encoder.encode(data);
    }
    
    public Map<String, Object> getDataMap() {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("name", "lichmama");
        dataMap.put("gender", "男");
        dataMap.put("birthday", "19**年**月**日");
        try {
            dataMap.put("image", getImageStr("D:\\頭像.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dataMap;
    }
    
    public void exportDoc(String doc, String name) throws Exception {
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(doc), encoding));
        getTemplate(name).process(getDataMap(), writer);
    }
    
    public static void main(String[] args) throws Exception {
        ExportDoc maker = new ExportDoc("UTF-8");
        maker.exportDoc("D:\\test.doc", "test.ftl");
    }
}

複製程式碼

生成的文件效果如下圖: