温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用java怎么替换docx文件中的字符串

发布时间:2021-02-07 18:17:55 来源:亿速云 阅读:299 作者:Leah 栏目:开发技术

这篇文章给大家介绍使用java怎么替换docx文件中的字符串,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

替换docx文件里面的 ${} 字符串

public class Main {
  public static void main(String[] args) throws Exception {
    String template = "C:\\Users\\lzh\\Desktop\\模板.docx";
    String outSrc = "C:\\Users\\lzh\\Desktop\\简历.docx";

    var is = new FileInputStream(template);
    var os = new FileOutputStream(outSrc);

    editDocx(os, is, xml -> {
      Map<String,String> map = new HashMap<>();
      map.put("${name}", "李**");
      map.put("${sex}", "男");
      map.put("${age}", "21");

      Pattern p = Pattern.compile("(\\$\\{)([\\w]+)(\\})");
      Matcher m = p.matcher(xml);
      StringBuffer sb = new StringBuffer();
      while (m.find()) {
        String group = m.group();
        m.appendReplacement(sb, map.get(group));
      }
      m.appendTail(sb);
      xml = sb.toString();

      return xml;
    });
  }

  public static void editDocx(OutputStream bos,InputStream is, Process process){
    ZipInputStream zin = new ZipInputStream(is);
    ZipOutputStream zos = new ZipOutputStream(bos);
    try {
      ZipEntry entry;
      while((entry = zin.getNextEntry()) != null) {
        //把输入流的文件传到输出流中 如果是word/document.xml由我们输入
        zos.putNextEntry(new ZipEntry(entry.getName()));
        if("word/document.xml".equals(entry.getName())){
          String xml = new BufferedReader(new InputStreamReader(zin)).lines().collect(Collectors.joining(System.lineSeparator()));
          xml = process.process(xml);

          ByteArrayInputStream byteIn = new ByteArrayInputStream(xml.getBytes());
          int c;
          while ((c = byteIn.read()) != -1) {
            zos.write(c);
          }
          byteIn.close();
        }else {
          int c;
          while ((c = zin.read()) != -1) {
            zos.write(c);
          }
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        zos.close();
        zin.closeEntry();
        zin.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

interface Process {
  String process(String xml);
}

关于使用java怎么替换docx文件中的字符串就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI