java 替换docx文件中的字符串方法实现
程序员文章站
2022-04-02 20:17:19
替换docx文件里面的 ${} 字符串public class main { public static void main(string[] args) throws exception {...
替换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文件中的字符串方法实现的文章就介绍到这了,更多相关java 替换docx字符串内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!