官网 | 中文官网
本文暂不介绍freemarker api,以案例的方式进行介绍。
项目引入freemarker
1 2 3 4 5
| <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.31</version> </dependency>
|
FreeMarker使用doc模板
使用doc模版,将数据引入。
模版示例:
结果示例:
- 先准备doc模版文件。将需要放入值的属性加上
${}
,如:${aa}
。
- 将准备好的doc文件转换成html文件。
- 将html文件放入同项目的templates中(如要调整存放文件位置,可以同步把下方工具类里路径也调整了。)
- 引入下方工具类。
- 使用工具类。
工具类可以根据个人需求进行调整。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| import com.ruoyi.common.config.RuoYiConfig; import com.ruoyi.common.core.domain.AjaxResult; import freemarker.template.Configuration; import freemarker.template.Template;
import java.io.*; import java.util.Map; import java.util.UUID;
public class WordUtil { private static Configuration configuration = null; static { configuration = new Configuration(); configuration.setDefaultEncoding("utf-8"); configuration.setClassForTemplateLoading(WordUtil.class, "/templates"); }
private WordUtil() { throw new AssertionError(); }
public static AjaxResult exportMillCertificateWord(Map map, String title, String ftlFile) throws IOException { Template freemarkerTemplate = configuration.getTemplate(ftlFile); String fileName = UUID.randomUUID().toString() + "_" + title + ".doc"; String downloadPath = RuoYiConfig.getDownloadPath() + fileName; File desc = new File(downloadPath); if (!desc.getParentFile().exists()) { desc.getParentFile().mkdirs(); } createDoc(map,freemarkerTemplate,downloadPath); return AjaxResult.success(fileName); }
private static File createDoc(Map<?, ?> dataMap, Template template, String name) { File f = new File(name); Template t = template; try { Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8"); t.process(dataMap, w); w.close(); } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } return f; } }
|
1 2 3 4 5 6 7 8
| Map map = new HashMap(); map.put("aa","张三"); map.put("bb","李四"); map.put("cc","王五"); map.put("dd","赵六"); map.put("ee","孙七"); return WordUtil.exportMillCertificateWord(map,"offer","test.html");
|
参考文档