// dataMap为所需要的数据, templetFilePath 模板路径 targetFilePath 生成的文档路径 public static Map<String, String> xml2XmlDoc(Map<String, Object> dataMap, String templetFilePath, String targetFilePath) { Map<String, String> map = new HashMap<>(); // 将模板文件路径拆分为文件夹路径和文件名称 String tempLetDir = templetFilePath.substring(0, templetFilePath.lastIndexOf("/")); // 注意:templetFilePath.lastIndexOf("/")中,有的文件分隔符为:\ 要注意文件路径的分隔符 String templetName = templetFilePath.substring(templetFilePath.lastIndexOf("/") + 1); // 将目标文件保存路径拆分为文件夹路径和文件名称 String targetDir = targetFilePath.substring(0, targetFilePath.lastIndexOf("/")); String targetName = targetFilePath.substring(targetFilePath.lastIndexOf("/") + 1); Configuration configuration = new Configuration(); configuration.setDefaultEncoding("UTF-8"); // 如果目标文件目录不存在,则需要创建 File file = new File(targetDir); if (!file.exists()) { file.mkdirs(); } // 加载模板数据(从文件路径中获取文件,其他方式,可百度查找) try { configuration.setDirectoryForTemplateLoading(new File(tempLetDir));// 获取模板实例 Template template = configuration.getTemplate(templetName); File outFile = new File(targetDir + File.separator + targetName); //将模板和数据模型合并生成文件 Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8")); //生成文件 template.process(dataMap, out); out.flush(); out.close(); map.put("status", "success"); map.put("fileName", targetName); map.put("filePath", targetDir + File.separator + targetName); } catch (IOException e) { map.put("status", "fail"); e.printStackTrace(); } catch (TemplateException e) { map.put("status", "fail"); e.printStackTrace(); } return map; }
XML+freemaker标签 转docx文档
最新推荐文章于 2024-09-20 17:09:44 发布