POI调用Word动态传参1功能描述实现动态传参给Word模板,然后替换模板中的参数,最后生成目的文档;传入参数分别是源文件路径,目的文件路径和匹配MAP2实现所需JAR包poi-scratchpad-3.8-20120326.jar(文档最后有提供)3代码实现://替换word中需要替换的特殊字符publicstaticbooleanreplaceWord(StringsrcPath,StringdestPath,MapString,Stringmap){String[]sp=srcPath.split(\\.);String[]dp=destPath.split(\\.);if((sp.length0)&&(dp.length0)){//判断文件有无扩展名//比较文件扩展名if(sp[sp.length-1].equalsIgnoreCase(docx)){try{XWPFDocumentdocument=newXWPFDocument(POIXMLDocument.openPackage(srcPath));//替换段落中的指定文字IteratorXWPFParagraphitPara=document.getParagraphsIterator();while(itPara.hasNext()){XWPFParagraphparagraph=(XWPFParagraph)itPara.next();Stringstr=paragraph.getText();for(Map.EntryString,Stringentry:map.entrySet()){str=str.replace(entry.getKey(),entry.getValue());}ListXWPFRunruns=paragraph.getRuns();for(inti=0;iruns.size();i++){if(runs.get(i)!=null){runs.get(i).setText(,0);//将所有的XWPFRun都置空}if(i==0){runs.get(i).setText(str,0);//将第一个XWPFRun的值存整个XWPFParagraph的字符串}}}//替换表格中的指定文字IteratorXWPFTableitTable=document.getTablesIterator();while(itTable.hasNext()){XWPFTabletable=(XWPFTable)itTable.next();intrcount=table.getNumberOfRows();for(inti=0;ircount;i++){XWPFTableRowrow=table.getRow(i);ListXWPFTableCellcells=row.getTableCells();for(XWPFTableCellcell:cells){StringcellTextString=cell.getText();for(EntryString,Stringe:map.entrySet()){if(cellTextString.contains(e.getKey()))cellTextString=cellTextString.replace(e.getKey(),e.getValue());}cell.removeParagraph(0);cell.setText(cellTextString);}}}FileOutputStreamoutStream=null;outStream=newFileOutputStream(destPath);document.write(outStream);outStream.close();returntrue;}catch(Exceptione){e.printStackTrace();returnfalse;}}else{returnfalse;}}else{returnfalse;}}调用参考如下:StringfilepathString=D:/2.docx;StringdestpathString=D:/2ttt.docx;MapString,Stringmap=newHashMapString,String();map.put(${BANKNAME},中信);map.put(${BANK},中信银行);map.put(${TRANNAME},亿量);map.put(${LAWYER},周攀);map.put(${YEAR},2015);map.put(${MONTH},09);map.put(${DAY},14);System.out.println(replaceWord(filepathString,destpathString,map));4模板和jar包2.docx