java替换文件中的字符串_java 替换docx文件中的字符串方法实现

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

4f10636dc8c3287a164a6fec99f19ed8.png

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 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文件中的字符串方法实现的文章就介绍到这了,更多相关java 替换docx字符串内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值