POI操作word2007(docx)文件的文本和图片

时间:2022-02-24 10:47:18

一、自定义重写poi中的方法:

[1].[文件] CustomXWPFDocument.java ~ 4KB 

importjava.io.IOException;  
importjava.io.InputStream;  
importorg.apache.poi.openxml4j.opc.OPCPackage;  
importorg.apache.poi.xwpf.usermodel.XWPFDocument;  
importorg.apache.poi.xwpf.usermodel.XWPFParagraph;  
importorg.apache.xmlbeans.XmlException;  
importorg.apache.xmlbeans.XmlToken;  
importorg.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;  
importorg.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;  
importorg.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;  
     
/**
 * 自定义 XWPFDocument,并重写 createPicture()方法 
 */ 
publicclass CustomXWPFDocument extendsXWPFDocument {    
    publicCustomXWPFDocument(InputStream in) throwsIOException {    
        super(in);   
    }   
     
    publicCustomXWPFDocument() {    
        super();   
    }   
     
    publicCustomXWPFDocument(OPCPackage pkg) throwsIOException {    
        super(pkg);   
    }   
     
    /**
     * @param id 
     * @param width 宽 
     * @param height 高 
     * @param paragraph  段落 
     */ 
    publicvoid createPicture(intid, intwidth, intheight,XWPFParagraph paragraph) {    
        finalint EMU = 9525;   
        width *= EMU;    
        height *= EMU;    
        String blipId = getAllPictures().get(id).getPackageRelationship().getId();    
        CTInline inline = paragraph.createRun().getCTR().addNewDrawing().addNewInline();    
        String picXml = ""   
                +"<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">"   
                +"   <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"   
                +"      <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"   
                +"         <pic:nvPicPr>" + "            <pic:cNvPr id=\""   
                + id    
                +"\" name=\"Generated\"/>"   
                +"            <pic:cNvPicPr/>"   
                +"         </pic:nvPicPr>"   
                +"         <pic:blipFill>"   
                +"            <a:blip r:embed=\""   
                + blipId    
                +"\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>"   
                +"            <a:stretch>"   
                +"               <a:fillRect/>"   
                +"            </a:stretch>"   
                +"         </pic:blipFill>"   
                +"         <pic:spPr>"   
                +"            <a:xfrm>"   
                +"               <a:off x=\"0\" y=\"0\"/>"   
                +"               <a:ext cx=\""   
                + width    
                +"\" cy=\""   
                + height    
                +"\"/>"   
                +"            </a:xfrm>"   
                +"            <a:prstGeom prst=\"rect\">"   
                +"               <a:avLst/>"   
                +"            </a:prstGeom>"   
                +"         </pic:spPr>"   
                +"      </pic:pic>"   
                +"   </a:graphicData>" + "</a:graphic>";   
     
        inline.addNewGraphic().addNewGraphicData();   
        XmlToken xmlToken = null;   
        try{    
            xmlToken = XmlToken.Factory.parse(picXml);    
        }catch(XmlException xe) {    
            xe.printStackTrace();   
        }   
        inline.set(xmlToken);  
           
        inline.setDistT(0);     
        inline.setDistB(0);     
        inline.setDistL(0);     
        inline.setDistR(0);     
           
        CTPositiveSize2D extent = inline.addNewExtent();    
        extent.setCx(width);   
        extent.setCy(height);   
           
        CTNonVisualDrawingProps docPr = inline.addNewDocPr();      
        docPr.setId(id);     
        docPr.setName("图片"+ id);      
        docPr.setDescr("测试");  
    }   
}   
?

[2].[文件] WordUtil.java ~ 7KB   

importjava.io.ByteArrayInputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
importjava.util.Map.Entry;
 
importorg.apache.poi.POIXMLDocument;
importorg.apache.poi.openxml4j.opc.OPCPackage;
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.usermodel.XWPFTableRow;
 
 
publicclass WordUtil {  
   
    /**
     * 根据指定的参数值、模板,生成 word 文档 
     * @param param 需要替换的变量 
     * @param template 模板 
     */ 
    publicstatic CustomXWPFDocument generateWord(Map<String, Object> param, String template) {  
        CustomXWPFDocument doc = null; 
        try{  
            OPCPackage pack = POIXMLDocument.openPackage(template);  
            doc = newCustomXWPFDocument(pack);  
            if(param != null&& param.size() > 0) {  
                   
                //处理段落 
                List<XWPFParagraph> paragraphList = doc.getParagraphs();  
                processParagraphs(paragraphList, param, doc);  
                   
                //处理表格 
                Iterator<XWPFTable> it = doc.getTablesIterator();  
                while(it.hasNext()) {  
                    XWPFTable table = it.next();  
                    List<XWPFTableRow> rows = table.getRows();  
                    for(XWPFTableRow row : rows) {  
                        List<XWPFTableCell> cells = row.getTableCells();  
                        for(XWPFTableCell cell : cells) {  
                            List<XWPFParagraph> paragraphListTable =  cell.getParagraphs();  
                            processParagraphs(paragraphListTable, param, doc);  
                        } 
                    } 
                } 
            } 
        }catch(Exception e) {  
            e.printStackTrace(); 
        } 
        returndoc;  
    } 
    /**
     * 处理段落 
     * @param paragraphList 
     */ 
    publicstatic void processParagraphs(List<XWPFParagraph> paragraphList,Map<String, Object> param,CustomXWPFDocument doc){ 
        if(paragraphList != null&& paragraphList.size() > 0){ 
            for(XWPFParagraph paragraph:paragraphList){  
                List<XWPFRun> runs = paragraph.getRuns();  
            
                    String text = "";
                    for(XWPFRun run : runs) 
                        text += run.getText(0);
                   // System.out.println(runs);
                    if(text != null){ 
                        booleanisSetText = false; 
                        for(Entry<String, Object> entry : param.entrySet()) {  
                            String key = entry.getKey();  
                            if(text.indexOf(key) != -1){ 
                                isSetText = true; 
                                Object value = entry.getValue();  
                                if(value instanceofString) {//文本替换 
                                    text = text.replace(key, value.toString());
                                }elseif (value instanceofMap) {//图片替换 
                                    text = text.replace(key, ""); 
                                    Map pic = (Map)value;  
                                    intwidth = Integer.parseInt(pic.get("width").toString()); 
                                    intheight = Integer.parseInt(pic.get("height").toString()); 
                                    intpicType = getPictureType(pic.get("type").toString()); 
                                    byte[] byteArray = (byte[]) pic.get("content"); 
                                    ByteArrayInputStream byteInputStream = newByteArrayInputStream(byteArray);  
                                    try{  
                                        intind = doc.addPicture(byteInputStream,picType);  
                                        doc.createPicture(ind, width , height,paragraph);
                                        System.out.println("图片替换");
                                    }catch(Exception e) {  
                                        e.printStackTrace(); 
                                    } 
                                } 
                            } 
                        } 
                        if(isSetText){ 
                            intflag = 1;
                            for(XWPFRun run : runs){
                                if(flag--==1)
                                    run.setText(text,0);
                                else
                                    run.setText("",0);
                             
                        } 
                    } 
                } 
            } 
        } 
    } 
    /**
     * 根据图片类型,取得对应的图片类型代码 
     * @param picType 
     * @return int 
     */ 
    privatestatic int getPictureType(String picType){  
        intres = CustomXWPFDocument.PICTURE_TYPE_PICT;  
        if(picType != null){ 
            if(picType.equalsIgnoreCase("png")){ 
                res = CustomXWPFDocument.PICTURE_TYPE_PNG;  
            }elseif(picType.equalsIgnoreCase("dib")){ 
                res = CustomXWPFDocument.PICTURE_TYPE_DIB;  
            }elseif(picType.equalsIgnoreCase("emf")){ 
                res = CustomXWPFDocument.PICTURE_TYPE_EMF;  
            }elseif(picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")){ 
                res = CustomXWPFDocument.PICTURE_TYPE_JPEG;  
            }elseif(picType.equalsIgnoreCase("wmf")){ 
                res = CustomXWPFDocument.PICTURE_TYPE_WMF;  
            } 
        } 
        returnres;  
    } 
    /**
     * 将输入流中的数据写入字节数组 
     * @param in 
     * @return 
     */ 
    publicstatic byte[] inputStream2ByteArray(InputStream in,booleanisClose){  
        byte[] byteArray = null; 
        try{  
            inttotal = in.available();  
            byteArray = newbyte[total]; 
            in.read(byteArray); 
        }catch(IOException e) {  
            e.printStackTrace(); 
        }finally{ 
            if(isClose){ 
                try{  
                    in.close(); 
                }catch(Exception e2) {  
                    System.out.println("关闭流失败"); 
                } 
            } 
        } 
        returnbyteArray;  
    } 
}

?

[3].[文件] Test.java ~ 2KB   

importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.util.HashMap;
importjava.util.Map;
 
 
publicclass Test {  
       
    publicstatic void main(String[] args) throwsException {  
           
        Map<String, Object> param = newHashMap<String, Object>();  
           
        Map<String,Object> header = newHashMap<String, Object>();  
        header.put("width",400); 
        header.put("height",150); 
        header.put("type","jpg"); 
        header.put("content", WordUtil.inputStream2ByteArray(newFileInputStream("C:\\new.jpg"),true));
        param.put("${img1}",header); 
         
         
        Map<String,Object> header2 = newHashMap<String, Object>();  
        header2.put("width",400); 
        header2.put("height",150); 
        header2.put("type","jpg"); 
        header2.put("content", WordUtil.inputStream2ByteArray(newFileInputStream("C:\\new.jpg"),true));
        param.put("${img2}",header2); 
         
           
        param.put("${table1}","1");
        param.put("${table2}","2");
        param.put("${table5}","5");
        param.put("${table3}","3");
        param.put("${param1}","oschina1");
        param.put("${param53}","oschina53");
         
         
        CustomXWPFDocument doc = WordUtil.generateWord(param, "C:\\Users\\James\\Desktop\\docmodelreplaced333.docx");
        FileOutputStream fopts = newFileOutputStream("C:\\Users\\James\\Desktop\\docmodelreplaced2.docx"); 
        doc.write(fopts); 
        fopts.close(); 
    } 
}
?

[4].[图片] DQ{T4[AH~WZ2}@0IY%8%)RH.png 

POI操作word2007(docx)文件的文本和图片

[5].[图片] 1[O5IC$J{8Y9@DY60~_2Q1Z.png 跳至 [1] [2] [3] [4] [5] [6]

POI操作word2007(docx)文件的文本和图片

[6].[图片] ][K}CR5TUG2JCKLY(J5%WVC.png 跳至 [1] [2] [3] [4] [5] [6]

POI操作word2007(docx)文件的文本和图片