java poi解析word(doc,docx)替换word模板中的占位符

doc类型的word用HWPFDocument类进行解析
docx类型的word用XWPFDocument类进行解析

/**
	 * 
	 * @param srcPath word模板数据源路径
	 * @param destPath word导出路径
	 * @param map 关键字键值对映射
	 * @throws Exception
	 */
	public static void replaceWord(String srcPath, String destPath,Map<String, String> map) throws Exception {
     
		FileOutputStream out = null;
		FileInputStream input = null;
		try {
     
			if("doc".equals(srcPath.split("\\.")[1])) {
     
				input = new FileInputStream(new File(srcPath));
				HWPFDocument document = new HWPFDocument(input);
				Range range = document.getRange();
				for(Map.Entry<String, String> entry : map.entrySet()) {
     
					 if (entry.getValue() == null) {
     
			                entry.setValue("  ");
			         }
					range.replaceText(entry.getKey(), entry.getValue());
				}
				ByteArrayOutputStream ostream = new ByteArrayOutputStream();
				out = new FileOutputStream(new File(destPath));
				document.write(out);
				out.write(ostream.toByteArray());
				out.flush();
			}else {
     
				XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(srcPath));
	            // 替换段落中的指定文字
	            Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
	            while (itPara.hasNext()) {
     
	                XWPFParagraph paragraph = itPara.next();
	                List<XWPFRun> runs = paragraph.getRuns();
	                for (XWPFRun run : runs) {
     
	                    String oneparaString = run.getText(run.getTextPosition());
	                    if (StringUtils.isBlank(oneparaString)){
     
	                        continue;
	                    }
	                    for (Map.Entry<String, String> entry :
	                            map.entrySet()) {
     
	                        oneparaString = oneparaString.replace(entry.getKey(), entry.getValue());
	                    }
	                    run.setText(oneparaString, 0);
	                }
	 
	            }
	            ByteArrayOutputStream ostream = new ByteArrayOutputStream();
				out = new FileOutputStream(new File(destPath));
				document.write(out);
				out.write(ostream.toByteArray());
				out.flush();

			}
			
			
			
		}catch (Exception e) {
     
			e.printStackTrace();
		} finally {
     
			if(out != null) {
     
				out.close();
			}
			if(input != null) {
     
				input.close();
			}
		}
	}

你可能感兴趣的:(java,poi,word,java)