欢迎来到天天文库
浏览记录
ID:42161575
大小:15.27 KB
页数:3页
时间:2019-09-09
《java用poi实现对word读取和修改操作》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
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.
2、POIXMLDocument;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.apa
3、che.poi.xwpf.usermodel.XWPFTableRow;publicclassWordUtil{publicstaticvoidsearchAndReplace(StringsrcPath,StringdestPath,Mapmap){try{XWPFDocumentdocument=newXWPFDocument(POIXMLDocument.openPackage(srcPath));//替换段落中的指定文字IteratoritPara=docume
4、nt.getParagraphsIterator();while(itPara.hasNext()){XWPFParagraphparagraph=(XWPFParagraph)itPara.next();//Strings=paragraph.getParagraphText();Setset=map.keySet();Iteratoriterator=set.iterator();while(iterator.hasNext()){Stringkey=iterator.next();List<
5、XWPFRun>runs=paragraph.getRuns();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);}}}}}/
6、/替换表格中的指定文字IteratoritTable=document.getTablesIterator();while(itTable.hasNext()){XWPFTabletable=(XWPFTable)itTable.next();intrcount=table.getNumberOfRows();for(inti=0;icells=row.getTableCells(
7、);for(XWPFTableCellcell:cells){for(Entrye:map.entrySet()){if(cell.getText().equals(e.getKey())){cell.removeParagraph(0);cell.setText(e.getValue());}}}}}FileOutputStreamoutStream=null;outStream=newFileOutputStream(destPath);document.write(outStream);out
8、Stream.close();}catch(Exceptione){e.printStackTrace();}}publicstaticvoidmain(String[]args)throwsException{Mapmap=new
此文档下载收益归作者所有