/** * 替换word中指定的内容 * @param tmpFile 待替换的文件 * @param contentMap 要替换的内容集合 key:书签名 value:待替换的内容 * @param exportFile 替换后的文件 * @throws Exception */ public void creatWordByModel(String tmpFile, Map<String, String> contentMap, String exportFile){ InputStream in = null; OutputStream outputStream=null; try { in = new FileInputStream(new File(tmpFile)); HWPFDocument document = null; document = new HWPFDocument(in); Bookmarks bookmarks = document.getBookmarks(); System.out.println(bookmarks); for(int dwI = 0;dwI < bookmarks.getBookmarksCount();dwI++){ Bookmark bookmark = bookmarks.getBookmark(dwI); if(contentMap.containsKey(bookmark.getName())){ Range range = new Range(bookmark.getStart(),bookmark.getEnd(),document); range.replaceText(contentMap.get(bookmark.getName()),false); } } //导出到文件 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); document.write((OutputStream)byteArrayOutputStream); outputStream = new FileOutputStream(exportFile); outputStream.write(byteArrayOutputStream.toByteArray()); } catch (IOException e) { e.printStackTrace(); }finally { try { if(in!=null){ in.close(); } if(outputStream!=null){ outputStream.close(); } } catch (IOException ioException) { ioException.printStackTrace(); } } }