Framemarker模板导出

    xiaoxiao2022-07-06  187

    1.首先创建word模板文件,把需要替换动态的数据使用字段代替。 2.文件另存为xml文档,使用编辑器打开文档,复制xml源码,(格式比较混乱,可以使用格式化xml编译器整理格式) xml格式化:http://tool.oschina.net/codeformat/xml/ 3.修改xml文件中需要替换的字段 4.针对成绩列表循环替换字段 结束标签 5.模板文件创建完毕,加入到项目中 6.写一个请求,整理好数据格式,做动态显示数据 //存放班级信息 Map<String, Object> dataMap = new HashMap<String, Object>(); dataMap.put(“class”, “八年二班”); dataMap.put(“teacher”, “老师”); //存放学生成绩信息列表 List<Map<String, Object>> reportList = new ArrayList<>(); Map<String, Object> reportMap = new HashMap<String, Object>(); reportMap.put(“name”, “张三”); reportMap.put(“number”, “20”); reportMap.put(“chinese”, “100”); reportMap.put(“math”, “99”); reportMap.put(“english”, “86”); reportMap.put(“total”, “86”); Map<String, Object> reportMap1 = new HashMap<String, Object>(); reportMap1.put(“name”, “李四”); reportMap1.put(“number”, “20”); reportMap1.put(“chinese”, “100”); reportMap1.put(“math”, “99”); reportMap1.put(“english”, “86”); reportMap1.put(“total”, “86”); Map<String, Object> reportMap2 = new HashMap<String, Object>(); reportMap2.put(“name”, “王五”); reportMap2.put(“number”, “20”); reportMap2.put(“chinese”, “100”); reportMap2.put(“math”, “99”); reportMap2.put(“english”, “86”); reportMap2.put(“total”, “86”); Map<String, Object> reportMap3 = new HashMap<String, Object>(); reportMap3.put(“name”, “赵六”); reportMap3.put(“number”, “20”); reportMap3.put(“chinese”, “100”); reportMap3.put(“math”, “99”); reportMap3.put(“english”, “86”); reportMap3.put(“total”, “86”); reportList.add(reportMap); reportList.add(reportMap1); reportList.add(reportMap2); reportList.add(reportMap3); dataMap.put(“reportList”, reportList); 7.获取模板信息,将数据动态加入生成文件。 try { //获取服务根路径 String path = Thread.currentThread().getContextClassLoader().getResource("").getPath(); System.out.println(path); Configuration configuration = new Configuration(); configuration.setDirectoryForTemplateLoading(new File(path+"/ftl")); configuration.setEncoding(Locale.getDefault(),“UTF-8”); Template template = configuration.getTemplate(“模板文件.ftl”); //template.process(dataMap,new OutputStreamWriter(System.out)); //生成文件的路径 /** 指定输出word文件的路径 **/ File f = new File(“D:\source2.docx”); FileOutputStream outputStream = new FileOutputStream(f); wirteur = new BufferedWriter(new OutputStreamWriter(outputStream,“UTF-8”),10240); template.process(dataMap, wirteur); } catch (IOException e) { e.printStackTrace(); } catch (TemplateException e) { e.printStackTrace(); }finally { wirteur.close(); }

    最新回复(0)