XML+freemaker标签 转docx文档

1 篇文章 0 订阅
1 篇文章 0 订阅
// 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值