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

private CustomXWPFDocument searchAndReplace(String srcPath, Map<String, Object> map) {
    try {
        CustomXWPFDocument document = new CustomXWPFDocument(POIXMLDocument.openPackage(srcPath));
        /**
         * 替换段落中的指定文字
         */
        Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
        while (itPara.hasNext()) {
            XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
            Set<String> set = map.keySet();
            Iterator<String> iterator = set.iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                List<XWPFRun> 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<XWPFTable> 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<XWPFTableCell> cells = row.getTableCells();
                for (XWPFTableCell cell : cells) {
                    for (Map.Entry<String, Object> 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 = ""
                + "<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=\""
                + 0
                + "\" 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(0);
        docPr.setName("pic" + id);
        docPr.setDescr("pic");
    }
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
使用JavaPOI库操作.doc Word模板替换并循环插入表格的步骤如下: 1. 导入POI库的相关依赖,例如Apache POI和Apache POI-OOXML。 2. 创建一个Word文档(.docx),该文档将作为模板使用。 3. 使用Apache POI的XWPFDocument类加载模板文档。 ```java XWPFDocument doc = new XWPFDocument(new FileInputStream("template.docx")); ``` 4. 声明一个XWPFTable对象,用于向文档中插入表格。 ```java XWPFTable table; ``` 5. 使用XWPFDocument类的getTables()方法获取文档中的所有表格,通常一个模板只有一个表格。 ```java List<XWPFTable> tables = doc.getTables(); table = tables.get(0); // 假设我们要操作的表格是第一个表格 ``` 6. 使用XWPFTable对象的removeRow()方法删除表格中的所有行,这样就可以将模板中的行删除,以便后面插入新的行。 ```java for (int i = table.getRows().size() - 1; i > 0; i--) { table.removeRow(i); } ``` 7. 使用XWPFTable对象的createRow()方法创建新的行,并使用XWPFTableRow对象的createCell()方法创建单元格。 ```java for (int i = 0; i < data.size(); i++) { XWPFTableRow newRow = table.createRow(); // 将data中的数据添加到新行的单元格中 for (int j = 0; j < data.get(i).size(); j++) { XWPFTableCell newCell = newRow.getCell(j); newCell.setText(data.get(i).get(j)); } } ``` 8. 将替换完表格的文档保存为新的文档。 ```java FileOutputStream out = new FileOutputStream("output.docx"); doc.write(out); out.close(); ``` 这样,你就可以使用JavaPOI库操作.doc Word模板替换表格并循环插入新的表格了。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值