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();
			}
		}
	} 
版权声明:本文为wxz980927155原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/wxz980927155/article/details/84945979