工具类 public class WordUtils { private static final Logger logger = LoggerFactory.getLogger(WordUtils.class); private final Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); public void createWord(String template, String docPath, Map<String, Object> dataMap) { // 加载文档模板FTL文件所存在的位置 configuration.setClassForTemplateLoading(this.getClass(), "/template"); configuration.setDefaultEncoding("UTF-8"); Template t; try { t = configuration.getTemplate(template); } catch (IOException e) { logger.error(e.getMessage(), e); throw new ServiceException("io读写模板失败!"); } //导出文件 File outFile = new File(docPath); Writer out; try { out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile))); } catch (FileNotFoundException e) { logger.error(e.getMessage(), e); throw new ServiceException("文件读取失败!"); } try { if (t != null) { //将填充数据填入模板文件并输出到目标文件 t.process(dataMap, out); } out.flush(); } catch (TemplateException | IOException e) { logger.error(e.getMessage(), e); throw new ServiceException("word生成失败!"); } finally { CloseUtil.closeQuietly(out); } } }
ftl文件所在位置
如何生成ftl文件
- 将 word 中需要填充的数据用占位符
${变量名}
替换。 - 将该 word 另存为 .xml 的格式,检查看格式是否有误(主要看占位符$有没被分割开来)
- 将后缀
.xml
改成.ftl
ftl文件处理
生成ftl所需dataMap