欢迎来到天天文库
浏览记录
ID:56044338
大小:15.26 KB
页数:3页
时间:2020-06-19
《java用poi实现对word读取和修改操作.doc》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、java用poi实现对word读取和修改操作新增WordUtil类,将代码拷进去直接运行即可packagecom.cjhxfund.ats.fm.instr;importjava.io.FileOutputStream;importjava.util.HashMap;importjava.util.Iterator;importjava.util.List;importjava.util.Map;importjava.util.Map.Entry;importjava.util.Set;importorg.apache.poi.POIXMLDo
2、cument;importorg.apache.poi.xwpf.usermodel.XWPFDocument;importorg.apache.poi.xwpf.usermodel.XWPFParagraph;importorg.apache.poi.xwpf.usermodel.XWPFRun;importorg.apache.poi.xwpf.usermodel.XWPFTable;importorg.apache.poi.xwpf.usermodel.XWPFTableCell;importorg.apache.poi.xwpf.use
3、rmodel.XWPFTableRow;publicclassWordUtil{publicstaticvoidsearchAndReplace(StringsrcPath,StringdestPath,Mapmap){try{XWPFDocumentdocument=newXWPFDocument(POIXMLDocument.openPackage(srcPath));//替换段落中的指定文字IteratoritPara=document.getParagraphsIterator
4、();while(itPara.hasNext()){XWPFParagraphparagraph=(XWPFParagraph)itPara.next();//Strings=paragraph.getParagraphText();Setset=map.keySet();Iteratoriterator=set.iterator();while(iterator.hasNext()){Stringkey=iterator.next();Listruns=paragraph.getRuns()
5、;for(XWPFRunrun:runs){Stringtext=run.getText(0);if(text!=null){//StringrunText=run.toString();if(text.indexOf(key)!=-1){text=text.replace(key,map.get(key));System.out.println("key=="+key+"~~~~runText=="+text);run.setText(text,0);}}}}}//替换表格中的指定文字IteratoritTable=do
6、cument.getTablesIterator();while(itTable.hasNext()){XWPFTabletable=(XWPFTable)itTable.next();intrcount=table.getNumberOfRows();for(inti=0;icells=row.getTableCells();for(XWPFTableCellcell:cells){for(Entry7、String>e:map.entrySet()){if(cell.getText().equals(e.getKey())){cell.removeParagraph(0);cell.setText(e.getValue());}}}}}FileOutputStreamoutStream=null;outStream=newFileOutputStream(destPath);document.write(outStream);outStream.close();}catch(Exceptione){e.printStackTrace();}}8、publicstaticvoidmain(String[]args)throwsException{Mapmap=new
7、String>e:map.entrySet()){if(cell.getText().equals(e.getKey())){cell.removeParagraph(0);cell.setText(e.getValue());}}}}}FileOutputStreamoutStream=null;outStream=newFileOutputStream(destPath);document.write(outStream);outStream.close();}catch(Exceptione){e.printStackTrace();}}
8、publicstaticvoidmain(String[]args)throwsException{Mapmap=new
此文档下载收益归作者所有