java 替換docx文件中的字符串方法實(shí)現(xiàn)
替換docx文件里面的 ${} 字符串
public class Main { public static void main(String[] args) throws Exception { String template = 'C:UserslzhDesktop模板.docx'; String outSrc = 'C:UserslzhDesktop簡(jiǎn)歷.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);}
到此這篇關(guān)于java 替換docx文件中的字符串方法實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)java 替換docx字符串內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. css代碼優(yōu)化的12個(gè)技巧2. xpath簡(jiǎn)介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理3. 三個(gè)不常見的 HTML5 實(shí)用新特性簡(jiǎn)介4. XHTML 1.0:標(biāo)記新的開端5. 告別AJAX實(shí)現(xiàn)無(wú)刷新提交表單6. CSS3中Transition屬性詳解以及示例分享7. CSS3使用過度動(dòng)畫和緩動(dòng)效果案例講解8. 使用css實(shí)現(xiàn)全兼容瀏覽器的三角形9. XML解析錯(cuò)誤:未組織好 的解決辦法10. 存儲(chǔ)于xml中需要的HTML轉(zhuǎn)義代碼
