1、新建一个word文档
2、把调整完的word另存为xml格式:
3、使用文本编辑器打开
4、xml格式化
XML 在线格式化 | 菜鸟工具菜鸟工具-XML 在线格式化../front-end/710/
5、选定动态生成范围,添加 list 标签
6、java代码
项目结构
导入依赖
<dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.23</version></dependency>
generateWord
/*** 使用FreeMarker自动生成Word文档** @param dataMap 生成Word文档所需要的数据* @param fileName 生成Word文档的全路径名称*/public static void generateWord(Map<String, Object> dataMap, String fileName, String templatePath, String template) throws Exception {// 设置FreeMarker的版本和编码格式Configuration configuration = new Configuration(new Version("2.3.23"));configuration.setDefaultEncoding("UTF-8");// 设置FreeMarker生成Word文档所需要的模板的路径configuration.setDirectoryForTemplateLoading(new File(templatePath));// 设置FreeMarker生成Word文档所需要的模板Template t = configuration.getTemplate(template, "UTF-8");// 创建一个Word文档的输出流Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileName)), "UTF-8"));//FreeMarker使用Word模板和数据生成Word文档t.process(dataMap, out);out.flush();out.close();}
调用
public static void main(String[] args) throws Exception {List<Test> lt=new ArrayList<>();Test t=new Test();t.setSeq(1);t.setName("测试01");t.setDes("测试01说明");lt.add(t);t=new Test();t.setSeq(2);t.setName("测试02");t.setDes("测试02说明");lt.add(t);t=new Test();t.setSeq(3);t.setName("测试03");t.setDes("测试03说明");lt.add(t);Map<String, Object> params = new HashMap<>();params.put("TestList", lt);String fileName="test.doc";generateWord(params, "src/main/resources/temp/" + fileName, "src/main/resources/word/", "TemplateV1.xml");}
生成效果
demo下载/download/lw112190/85122047