freemarker初體驗,導出dox文檔

1.Freemarker簡介

FreeMarker是一款模板引擎: 即一種基於模板和要改變的數據, 並用來生成輸出文本(HTML網頁、電子郵件配置文件源代碼等)的通用工具。 它不是面向最終用戶的,而是一個Java類庫,是一款程序員可以嵌入他們所開發產品的組件。

2.使用freemark導出doc文檔

2.1設置ftl文件模板

新建一個doc文檔,內容如下

然後另存爲xml文件,如圖:

使用文本編輯器打開xml文件,找到佔位符 ${username} 和 ${tool} 確保不被xml標籤分割,除此之外,還有一個很長的base64編碼的字符串文本,這個就是圖片,我們把這個文本刪掉,使用 ${imgStr} 替換。如圖:

最後修改xml後綴名稱爲ftl

2.2 編碼導出doc文檔

package com.yuwen;

import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * className: Domain <br/>
 * packageName:com.yuwen <br/>
 *
 * @author yuwen <br/>
 * @date: 2019-11-12 21:50 <br/>
 */
public class Domain {

    public static void main(String[] args) throws Exception {
        // 模板所在文件夾
        File dir = new File(Domain.class.getClassLoader().getResource("").getPath() + "/ftl");
        // 圖片路徑
        String imgpPath = Domain.class.getClassLoader().getResource("").getPath() + "img/timg.jpg";
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("username", "玉皇大帝");
        dataMap.put("tool", "freemaker");
        dataMap.put("imgStr", getImgStr(imgpPath));
        ExportDoc.export(dataMap, dir, "新建 Microsoft Word 文檔.ftl");
    }

    /**
     * 獲取指定文件圖片的base64字符串
     *
     * @param imgPath
     * @return
     */
    public static String getImgStr(String imgPath) throws Exception {
        FileInputStream fileInputStream = new FileInputStream(new File(imgPath));
        byte[] b = new byte[fileInputStream.available()];
        fileInputStream.read(b);
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return b.length == 0 ? "" : base64Encoder.encode(b);
    }
}

 

package com.yuwen;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Map;

/**
 * className: ExportDoc <br/>
 * packageName:java.com.yuwen <br/>
 *
 * @author yuwen <br/>
 * @date: 2019-11-12 21:43 <br/>
 */
public class ExportDoc {

    public static void export(Map<String, Object> dataMap, File dir, String fileName) throws Exception {

        // 1.新建配置對象,設置版本號,版本號與pom中引入的一致
        Configuration configuration = new Configuration(new Version("2.3.28"));
        // 2.設置字符集
        configuration.setDefaultEncoding("UTF-8");
        // 3.設置加載模板的文件夾(.ftl模板文件所在文件夾)
        configuration.setDirectoryForTemplateLoading(dir);
        // 4.獲取模板並且設置字符集
        Template template = configuration.getTemplate(fileName, "UTF-8");
        // 5.構造目標文件的輸出流
        File file = new File("D:/" + fileName.substring(0, fileName.lastIndexOf(".")) + ".doc");
        Writer writer = new FileWriter(file);
        // 6.構建doc文檔
        template.process(dataMap, writer);
        System.out.println("構建完成,文件路徑:" + file.getPath());

    }
}

 以上

 

沒積分打賞得留下qq郵箱即可

 

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