JAVA POI组件 针对Word模版替换 V2 可替换图片

private CustomXWPFDocument searchAndReplace(String srcPath, Map map) {
    try {
        CustomXWPFDocument document = new CustomXWPFDocument(POIXMLDocument.openPackage(srcPath));
        /**
         * 替换段落中的指定文字
         */
        Iterator itPara = document.getParagraphsIterator();
        while (itPara.hasNext()) {
            XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
            Set set = map.keySet();
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                List run = paragraph.getRuns();
                for (int i = 0; i < run.size(); i++) {
                    if (run.get(i).getText(run.get(i).getTextPosition()) != null &&
                            run.get(i).getText(run.get(i).getTextPosition()).equals(key)) {
                        /**
                         * 参数0表示生成的文字是要从哪一个地方开始放置,设置文字从位置0开始
                         * 就可以把原来的文字全部替换掉了
                         */
                        run.get(i).setText((String) map.get(key), 0);
                    }
                }
            }
        }

        /**
         * 替换表格中的指定文字
         */
        Iterator itTable = document.getTablesIterator();
        while (itTable.hasNext()) {
            XWPFTable table = (XWPFTable) itTable.next();
            int count = table.getNumberOfRows();
            for (int i = 0; i < count; i++) {
                XWPFTableRow row = table.getRow(i);
                List cells = row.getTableCells();
                for (XWPFTableCell cell : cells) {
                    for (Map.Entry e : map.entrySet()) {
                        if (cell.getText().equals(e.getKey())) {
                            Object ot = e.getValue();
                            if (ot instanceof String) {
				cell.removeParagraph(0);
				String q= (String)e.getValue();
				if (q.indexOf("\r")>0){
				   String[] oq=  q.split("\\r\\n");
				   for(String item : oq){
				       XWPFParagraph p =  cell.addParagraph();
				       p.createRun().setText(item);
				   }
				}else{
				    cell.setText(q);
				}                            } else if (ot instanceof Map) {
                                cell.removeParagraph(0);
                                XWPFParagraph imp = cell.addParagraph();
                                Map pic = (Map) ot;
                                int width = Integer.parseInt(pic.get("width").toString());
                                int height = Integer.parseInt(pic.get("height").toString());
                                int picType = getPictureType(pic.get("type").toString());
                                byte[] byteArray = (byte[]) pic.get("content");
                                ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray);
                                try {
                                    String ind = document.addPictureData(byteInputStream, picType);
                                    document.createPicture(ind, width, height, imp);
                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
        }
        return document;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
private int getPictureType(String picType) {
    int res = CustomXWPFDocument.PICTURE_TYPE_PICT;
    if (picType != null) {
        if (picType.equalsIgnoreCase("png")) {
            res = CustomXWPFDocument.PICTURE_TYPE_PNG;
        } else if (picType.equalsIgnoreCase("dib")) {
            res = CustomXWPFDocument.PICTURE_TYPE_DIB;
        } else if (picType.equalsIgnoreCase("emf")) {
            res = CustomXWPFDocument.PICTURE_TYPE_EMF;
        } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) {
            res = CustomXWPFDocument.PICTURE_TYPE_JPEG;
        } else if (picType.equalsIgnoreCase("wmf")) {
            res = CustomXWPFDocument.PICTURE_TYPE_WMF;
        }
    }
    return res;
}
public byte[] inputStream2ByteArray(InputStream in,boolean isClose){
    byte[] byteArray = null;
    try {
        int total = in.available();
        byteArray = new byte[total];
        in.read(byteArray);
    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        if(isClose){
            try {
                in.close();
            } catch (Exception e2) {
                System.out.println("关闭流失败");
            }
        }
    }
    return byteArray;
}
此段代码是替换图片所需的.在上个版本上增加了对图片的处理
下面需要进行对createPicture 进行重写.
因为我的模版只有1张图片,所以粉色这块为0  如果有其他的需
求,可对次参数,进行传参或者计算,一定要对上,不然文档打不开
package common.word;

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by lilin on 2017/10/13.
 */
public class CustomXWPFDocument extends XWPFDocument {
    public CustomXWPFDocument(InputStream in) throws IOException {
        super(in);
    }

    public CustomXWPFDocument() {
        super();
    }

    public CustomXWPFDocument(OPCPackage pkg) throws IOException {
        super(pkg);
    }

    /**
     * @param blipId
     * @param width 宽
     * @param height 高
     * @param paragraph  段落
     */
    public void createPicture(String id, int width, int height,XWPFParagraph paragraph) {
        final int EMU = 9525;
        width *= EMU;
        height *= EMU;
       String blipId = getAllPictures().get(0).getPackageRelationship().getId();
        if (paragraph == null) {
            paragraph = createParagraph();
        }
        CTInline inline = paragraph.createRun().getCTR().addNewDrawing().addNewInline();
        String picXml = ""
                + ""
                + "   "
                + "      "
                + "         " + "            "
                + "            "
                + "         "
                + "         "
                + "            "
                + "            "
                + "               "
                + "            "
                + "         "
                + "         "
                + "            "
                + "               "
                + "               "
                + "            "
                + "            "
                + "               "
                + "            "
                + "         "
                + "      "
                + "   " + "";

        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(0);
        docPr.setName("pic" + id);
        docPr.setDescr("pic");
    }
}

 

你可能感兴趣的:(java)