java/poi读取word,并替换word中的文本内容,向word中插入图片的操作

先贴代码,注:部分代码源自网络其他前辈的文章,这里只是做一个功能整合。

[html]  view plain  copy
  1. package fcjTool;    
  2.     
  3. import java.io.IOException;    
  4. import java.io.InputStream;    
  5.     
  6.   
  7. import org.apache.poi.openxml4j.opc.OPCPackage;    
  8. import org.apache.poi.xwpf.usermodel.XWPFDocument;    
  9. import org.apache.poi.xwpf.usermodel.XWPFParagraph;  
  10. import org.apache.xmlbeans.XmlException;    
  11. import org.apache.xmlbeans.XmlToken;    
  12. import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;    
  13. import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;    
  14. import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;    
  15.     
  16. public class CustomXWPFDocument extends XWPFDocument {  
  17.     public CustomXWPFDocument(InputStream in) throws IOException {  
  18.         super(in);  
  19.     }  
  20.       
  21.     public CustomXWPFDocument() {  
  22.         super();  
  23.     }  
  24.       
  25.     public CustomXWPFDocument(OPCPackage pkg) throws IOException {  
  26.         super(pkg);  
  27.     }  
  28.       
  29.     public void createPicture(int id, int width, int height,XWPFParagraph paragraph) {  
  30.         final int EMU = 9525;  
  31.         width *= EMU;  
  32.         height *= EMU;  
  33.         String blipId = getAllPictures().get(id).getPackageRelationship()  
  34.                 .getId();      
  35.       
  36.         CTInline inline = paragraph.createRun().getCTR()      
  37.                 .addNewDrawing().addNewInline();      
  38.       
  39.         String picXml = ""      
  40.                 + "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">"      
  41.                 + "   <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"      
  42.                 + "      <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"      
  43.                 + "         <pic:nvPicPr>" + "            <pic:cNvPr id=\""      
  44.                 + id      
  45.                 + "\" name=\"Generated\"/>"      
  46.                 + "            <pic:cNvPicPr/>"      
  47.                 + "         </pic:nvPicPr>"      
  48.                 + "         <pic:blipFill>"      
  49.                 + "            <a:blip r:embed=\""      
  50.                 + blipId      
  51.                 + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>"      
  52.                 + "            <a:stretch>"      
  53.                 + "               <a:fillRect/>"      
  54.                 + "            </a:stretch>"      
  55.                 + "         </pic:blipFill>"      
  56.                 + "         <pic:spPr>"      
  57.                 + "            <a:xfrm>"      
  58.                 + "               <a:off x=\"0\" y=\"0\"/>"      
  59.                 + "               <a:ext cx=\""      
  60.                 + width      
  61.                 + "\" cy=\""      
  62.                 + height      
  63.                 + "\"/>"      
  64.                 + "            </a:xfrm>"      
  65.                 + "            <a:prstGeom prst=\"rect\">"      
  66.                 + "               <a:avLst/>"      
  67.                 + "            </a:prstGeom>"      
  68.                 + "         </pic:spPr>"      
  69.                 + "      </pic:pic>"      
  70.                 + "   </a:graphicData>" + "</a:graphic>";      
  71.       
  72.         inline.addNewGraphic().addNewGraphicData();  
  73.         XmlToken xmlToken = null;  
  74.         try {      
  75.             xmlToken = XmlToken.Factory.parse(picXml);  
  76.         } catch (XmlException xe) {      
  77.             xe.printStackTrace();      
  78.         }      
  79.         inline.set(xmlToken);      
  80.       
  81.         inline.setDistT(0);      
  82.         inline.setDistB(0);      
  83.         inline.setDistL(0);      
  84.         inline.setDistR(0);      
  85.       
  86.         CTPositiveSize2D extent = inline.addNewExtent();      
  87.         extent.setCx(width);      
  88.         extent.setCy(height);      
  89.       
  90.         CTNonVisualDrawingProps docPr = inline.addNewDocPr();      
  91.         docPr.setId(id);      
  92.         docPr.setName("图片" + id);      
  93.         docPr.setDescr("descr");      
  94.     }      
  95. }  


此类为操作word文本内容的具体实现类


[html]  view plain  copy
  1. package fcjTool;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStream;  
  8. import java.util.Iterator;  
  9. import java.util.List;  
  10.   
  11. import org.apache.poi.POIXMLDocument;  
  12. import org.apache.poi.openxml4j.opc.OPCPackage;  
  13. import org.apache.poi.xwpf.usermodel.XWPFDocument;  
  14. import org.apache.poi.xwpf.usermodel.XWPFParagraph;  
  15. import org.apache.poi.xwpf.usermodel.XWPFRun;  
  16. import org.apache.poi.xwpf.usermodel.XWPFTable;  
  17. import org.apache.poi.xwpf.usermodel.XWPFTableCell;  
  18. import org.apache.poi.xwpf.usermodel.XWPFTableRow;  
  19.   
  20. /**  
  21.  * 使用POI,读取word 2007,并实现修改文本内容,在指定位置插入图片,替换表格中的文本内容,并写回到word中  
  22.  * @author 付程俊  
  23.  *  
  24.  */  
  25. public class POIReadAndWriteWord2007 {  
  26.     public static void main(String[] args) {  
  27.         /**源文件的路径,注:只支持word2007,或许还支持word 2010,其他待测试*/  
  28.         String filePath = "E:\\test\\POIRedAndWrite.docx";  
  29.         String tips = POIReadAndWriteWord2007.readwriteWord(filePath);  
  30.         System.out.println(tips);  
  31.     }  
  32.     /**读取并操作word2007中的内容*/  
  33.     public static String readwriteWord(String filePath){  
  34.         File isExist = new File(filePath);  
  35.         /**判断源文件是否存在*/  
  36.         if(!isExist.exists()){  
  37.             return "源文件不存在!";  
  38.         }  
  39.         CustomXWPFDocument document;  
  40.         try {  
  41.             /**打开word2007的文件*/  
  42.             OPCPackage opc = POIXMLDocument.openPackage(filePath);  
  43.             document = new CustomXWPFDocument(opc);  
  44.             /**替换word2007的纯文本内容*/  
  45.             List<XWPFRun> listRun;  
  46.             List<XWPFParagraph> listParagraphs = document.getParagraphs();  
  47.             for (int i = 0; i < listParagraphs.size(); i++) {  
  48.                 listRun = listParagraphs.get(i).getRuns();  
  49.                 for (int j = 0; j < listRun.size(); j++) {  
  50.                     if("#{text}#".equals(listRun.get(j).getText(0))){  
  51.                         listRun.get(j).setText("替换的纯文本内容!",0);  
  52.                     }  
  53.                 }  
  54.             }  
  55.             /**取得文本的所有表格*/  
  56.             Iterator<XWPFTable> it = document.getTablesIterator();  
  57.             while(it.hasNext()){/**循环操作表格*/  
  58.                 XWPFTable table = it.next();  
  59.                 List<XWPFTableRow> rows = table.getRows();  
  60.                 for(XWPFTableRow row:rows){/**取得表格的行*/  
  61.                     List<XWPFTableCell> cells = row.getTableCells();  
  62.                     for(XWPFTableCell cell:cells){/**取得单元格*/  
  63.                         if("#{img}#".equals(cell.getText())){/**判断单元格的内容是否为需要替换的图片内容*/  
  64.                             File pic = new File("E:\\test\\xiaosimm.png");  
  65.                             FileInputStream is = new FileInputStream(pic);  
  66.                             cell.removeParagraph(0);  
  67.                             XWPFParagraph pargraph = cell.addParagraph();  
  68.                             document.addPictureData(is, XWPFDocument.PICTURE_TYPE_PNG);  
  69.                             document.createPicture(document.getAllPictures().size()-1, 600, 395, pargraph);  
  70.                             if(is != null){  
  71.                                 is.close();  
  72.                             }  
  73.                         }  
  74.                         List<XWPFParagraph> pars = cell.getParagraphs();  
  75.                         for(XWPFParagraph par:pars){  
  76.                             List<XWPFRun> runs = par.getRuns();  
  77.                             for(XWPFRun run:runs){  
  78.                                 run.removeBreak();  
  79.                             }  
  80.                         }  
  81.                         if("#{table}#".equals(cell.getText())){/**判断单元格中是否为需要替换的文本内容*/  
  82.                             cell.removeParagraph(0);  
  83.                             cell.setText("替换表格中的文本内容!");  
  84.                         }  
  85.                     }  
  86.                 }  
  87.             }  
  88.             String downloadPath = "D:\\replace.docx";  
  89.             OutputStream os = new FileOutputStream(downloadPath);  
  90.             document.write(os);  
  91.             if(os != null){  
  92.                 os.close();  
  93.             }  
  94.             if(opc != null){  
  95.                 opc.close();  
  96.             }  
  97.             return "文件转换成功!路径为:"+downloadPath;  
  98.         } catch (Exception e) {  
  99.             e.printStackTrace();  
  100.         }  
  101.         return filePath;  
  102.     }  
  103.   
  104.     /**复制文件的方法*/  
  105.     public static void copyFile(String oldPath, String newPath) {  
  106.         try {  
  107.             int bytesum = 0;  
  108.             int byteread = 0;  
  109.             File oldfile = new File(oldPath);  
  110.             if (oldfile.exists()) { //文件存在时  
  111.                 InputStream inStream = new FileInputStream(oldPath); //读入原文件  
  112.                 FileOutputStream fs = new FileOutputStream(newPath);  
  113.                 byte[] buffer = new byte[1444];  
  114.                 while ( (byteread = inStream.read(buffer)) != -1) {  
  115.                     bytesum += byteread; //字节数 文件大小  
  116.                     System.out.println(bytesum);  
  117.                     fs.write(buffer, 0, byteread);  
  118.                 }  
  119.                 inStream.close();  
  120.                 fs.close();  
  121.             }  
  122.         }  
  123.         catch (Exception e) {  
  124.             System.out.println("复制单个文件操作出错");  
  125.             e.printStackTrace();  
  126.         }  
  127.     }  
  128. }  


注:此操作只支持word2007及以上版本。在指定位置插入图片时,必须将需要替换的文本放在单元格中。文件操作完后,会对源文件也进行操作,也就是会将源文件的需要替换的内容也替换掉,就不能达到重复利用源文件的效果,因此我在下面贴出了复制文件的方法,将源文件复制一份,再对复制文件进行操作,这样就可以使源文件多次复用。
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值