使用FreeMark+SpringBoot生成Word模板
word内容如下
姓名:${userName}
日期:${date}
标题 | 内容 |
${list.title} | ${list.content} |
然后将word文件另存为.xml文件,再将.xml文件的后缀名改为.ftl(freeMark模板)
将.ftl文件用Idea打开,使用ctrl+alt+l可格式化内容。转化后会存在"${}"被强制隔开的问题,需手动将隔开之间的文本删除
例如:
<w:t>$<w:t><w:t><w:t><w:t><w:t>{remark!" "}</w:t>
删除后:
<w:t>${remark!" "}</w:t>
之后进行字段组装
Map<String, Object> dataMap = new HashMap<>(); dataMap.put("userName","123"); dataMap.put("date","2010-1-3");
列表循环组装
List<Map<String, Object>> heads = new ArrayList<>(); for(int i = 0;i <standardProjectEntity.getHeads().size(); i ++){ Map<String, Object> map = new HashMap<>(); map.put("title",i); map.put("content",i-1); heads.add(map); } dataMap.put("list", heads);
之后进行文件输出
Configuration configuration = new Configuration(Configuration.VERSION_2_3_29); //设置编码 configuration.setDefaultEncoding("UTF-8"); //ftl模板文件 configuration.setClassForTemplateLoading(WordUtil.class,"/wordTemplate"); //获取模板 Template template = configuration.getTemplate(templateName); //将模板和数据模型合并生成文件 out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)); //生成文件 template.process(dataMap, out);