第一步就是將World文檔里面需要從數據庫填充的部分用占位符替換
第二步:就是將此文檔保存為Xml格式
第三步:將其放在resource目錄下,並選中此文件,右鍵點擊properties屬性,將其編碼格式設置為Utf-8(防止生成之后亂碼)
第四步:將此文件后綴名改為ftl
第五步:需要導入freemarker相關jar包
<!-- freemarker開始 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<!-- freemarker結束 -->
第六步:開始寫java代碼,我這是寫的一個測試類,當然你也可以和spring整合在一起
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class Test {
public static void main(String[] args) throws IOException, TemplateException {
//1.創建配置類
Configuration configuration = new Configuration(Configuration.getVersion());
//2.設置模板所在的目錄
configuration.setDirectoryForTemplateLoading(new File("C:/Eclipse_Workspace/jttx_record/src/main/resources"));
//C:\Eclipse_Workspace\jttx_record\src\main\resources\test.ftl
//3.設置字符集
configuration.setDefaultEncoding("utf-8");
//4.加載模板
Template template = configuration.getTemplate("tt.ftl");
//5.創建數據模型
Map map=new HashMap();
map.put("name", "甄士隱 ");
map.put("date","賈不假,白玉為堂金做馬,阿房宮,三百里,住不下金陵一個史,東海缺少白玉床,龍王請來金陵王,豐年好大雪,珍珠如土金如鐵,賈不假,白玉為堂金做馬,阿房宮,三百里,住不下金陵一個史,東海缺少白玉床,龍王請來金陵王,豐年好大雪,珍珠如土金如鐵");
//6.創建 Writer 對象
Writer out =new FileWriter(new File("C:\\Users\\jttx_record\\Desktop\\tt.doc"));
//7.
template.process(map, out);
//8.關閉 Writer 對象
out.close();
}
}
至此:java使用模板引擎導出World文檔到此結束