首先需要一个word
文件作为模板,例如
${name}
是将要替换的变量。 在需要的地方,放上变量会自动替换。如果定义了变量却没有值来替换,会报错。
导入依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
关键代码
@Override
public Map<String,Object> getDimensionAreaData(ParameterVO parameterVO) {
try {
Configuration configuration = new Configuration(new Version("2.3.0"));
configuration.setDefaultEncoding("utf-8");
/**
* 以下是两种指定ftl文件所在目录路径的方式,注意这两种方式都是
* 指定ftl文件所在目录的路径,而不是ftl文件的路径
*/
configuration.setClassForTemplateLoading(this.getClass(), "");
//指定路径的第二种方式,我的路径是D:/Hard Disk E/DesKtop/
configuration.setDirectoryForTemplateLoading(new File("D:/Hard Disk E/DesKtop/"));
//输出文档路径及名称
String src_file = "";
if (osName.toLowerCase().startsWith("win")) {
src_file = uploadWindows + "/zidongbaogao/";
} else {
src_file = uploadLinux + "/zidongbaogao/";
}
File dir = new File(src_file);
if (!dir.exists()) {
dir.mkdirs();
}
tring fileName ="我太帅了.doc";
File outFile = new File(src_file + fileName);
//以utf-8的编码读取ftl文件
Template template = configuration.getTemplate("根据厅办调研背景材料省模板060301.ftl", "utf-8");
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
// 如果写入的变量有 ‘<’ '>' 需要替换一下
// template.toString().replaceAll("<", "<");
// template.toString().replaceAll(">", ">");
Map<String,String> dataMap = new HashMap<String,String>();
dataMap.put("name", "china");
template.process(dataMap, out);
out.close();
}
} catch (Exception e) {
logger.error(e.getMessage());
}
}
原始的参考文档已经找不到了。。。
这里更完整一些 https://blog.csdn.net/Carolxiaobai/article/details/86479446