poi替换文档指定的内容

在公司做开发的时候,遇见了一个难题,就是将一份本地的指定内容给隐藏掉。不说废话,直接上代码

    /**
     * Info 将docx的文档的内容把指定的内容替换掉
     * Modification History:
     * Date         Author      Version     Description
     * -----------------------------------------------------------------
     * 2018-1-5        ywl       v1.0.0       create
     * -----------------------------------------------------------------
     * @param srcPath 原路径
     * @param destPath 保存路径
     * @map key为需要替换的 value为替换的内容
     */
    public static void searchAndReplace(String srcPath, String destPath,Map map) {
        FileOutputStream outStream = null;
        InputStream is = null;
        try {
            URL url = new URL(srcPath);
            is = url.openStream();
            XWPFDocument document = new XWPFDocument(is);
            /**
             * 替换段落中的指定文字
             */
            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 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())) {
                                cell.removeParagraph(0);
                                cell.setText(e.getValue());
                            }
                        }
                    }
                }
            }
            outStream = new FileOutputStream(destPath); 
            document.write(outStream);
//            URLConnection conn = url.openConnection();
//            conn.setDoOutput(true);
//            outStream = conn.getOutputStream();
//            document.write(outStream);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(null != is){
                    is.close();
                }
                if(null != outStream){
                    outStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
代码很简单,直接拿去用就行了。原路径是远程的路径,如果是本地的路径,只需要
URL url = new URL(srcPath);
is = url.openStream();
is = new FileInputStream(new File(srcPath));

第一个路径是打开的url,第二个是打开的本地的,感觉不难,如果不会的,在留言板留言。 
  

如果你觉得我写的还可以,请关注我的公众号,为我加油喝彩

poi替换文档指定的内容_第1张图片

你可能感兴趣的:(java)