[poi-tl]转换html内容到word

  baikapala

    利用jsoup将html解析,递归解析,将不同的html标签内容转换成poi支持的内容。代码仅供参考。

    
    private static AbstractRenderPolicy createCaseStepResultRenderPolicy() {
        return new AbstractRenderPolicy() {
            @Override
      protected void afterRender(RenderContext context) {
                // 清空模板标签所在段落
      clearPlaceholder(context, true);
            }
    
            @Override
      public void doRender(RunTemplate runTemplate, Object data, XWPFTemplate template) throws Exception {
                if (data == null || StringUtils.isBlank(data.toString())) {
                    return;
                }
    
                //获得Apache POI增强类NiceXWPFDocument
      NiceXWPFDocument doc = template.getXWPFDocument();
    
                String html = data.toString();
                html.replaceAll(">", ">");
                html.replaceAll("&lt;", "<");
                html.replaceAll("&nbsp;", " ");
                html.replaceAll("\\n", "");
                html.replaceAll("<br>", "\n");
                org.jsoup.nodes.Document htmlDoc = Jsoup.parse(html);
                Elements nodes = htmlDoc.body().children();
                XWPFParagraph xwpfParagraph = doc.createParagraph();
    
                ListIterator itr = nodes.listIterator();
                while (itr.hasNext()) {
                    Element e = itr.next();
                    xwpfParagraph = parseHtmlToWord(e, doc, xwpfParagraph, "body");
                }
            }
        };
    }
    
    /**
     * 转换整个html内容为word内容
      * @author xuwangcheng
     * @date 2019/7/29 18:46
     * @param ele ele
     * @param doc doc
     * @param xwpfParagraph xwpfParagraph
     * @param parentTagName parentTagName
     * @return {@link XWPFParagraph}
     */private static XWPFParagraph parseHtmlToWord(Element ele, NiceXWPFDocument doc, XWPFParagraph xwpfParagraph, String parentTagName) throws Exception {
        if (ReUtil.isMatch("(p|h[12345]|li|img)", ele.tagName())) {
            xwpfParagraph = doc.createParagraph();
        }
    
        //处理img图片
      if ("img".equals(ele.tagName())) {
            parseImgToWord(ele.attr("src"), xwpfParagraph);
            return xwpfParagraph;
        }
    
        //处理table标签
      if ("table".equals(ele.tagName())) {
            parseTableToWord(doc, ele);
            return xwpfParagraph;
        }
    
        String text = ele.wholeText();
        if (StringUtils.isNotBlank(text)) {
            TextRenderPolicy.Helper.renderTextRun(xwpfParagraph.createRun()
                    , new TextRenderData(text));
            return xwpfParagraph;
        }
    
        if (ele.children().size() > 0) {
            ListIterator itr = ele.children().listIterator();
            while (itr.hasNext()) {
                Element me = itr.next();
                xwpfParagraph = parseHtmlToWord(me, doc, xwpfParagraph, ele.tagName());
            }
        }
    
        return xwpfParagraph;
    }
    
    /**
     * 转换图片为word内容
      * @author xuwangcheng
     * @date 2019/7/29 18:45
     * @param imgUrl imgUrl
     * @param xwpfParagraph xwpfParagraph
     */private static void parseImgToWord(String imgUrl, XWPFParagraph xwpfParagraph) throws Exception {
        //获取图片本地路径
      FileInfoService fileInfoService = SpringContextUtils.getBean(FileInfoService.class);
        FileInfoEntity fileInfoEntity = fileInfoService.queryByUrlPath(imgUrl.trim());
        if (fileInfoEntity == null || !FileUtil.exist(fileInfoEntity.getRealPath())) {
            return;
        }
    
        //插入图片
      //获取图片对象
      BufferedImage img = ImageIO.read(new File(fileInfoEntity.getRealPath()));
        //获得图片的宽
      int width = img.getWidth();
        //获得图片的高
      int height = img.getHeight();
        if (width > 600) {
            //获取比例
      int rate = (width / 600 ) + 1;
            width = width / rate - 20;
            height = height / rate;
        }
        PictureRenderData pictureRenderData = new PictureRenderData(width, height, fileInfoEntity.getRealPath());
        PictureRenderPolicy.Helper.renderPicture(xwpfParagraph.createRun(), pictureRenderData);
    }
    
    /**
     * 转换表格为word内容
      * @author xuwangcheng
     * @date 2019/7/29 18:45
     * @param doc doc
     * @param ele ele
     */private static void parseTableToWord(NiceXWPFDocument doc, Element ele) {
        //简化表格html
      org.jsoup.nodes.Document tableDoc = Jsoup.parse(simplifyTable(ele.outerHtml()));
        Elements trList = tableDoc.getElementsByTag("tr");
        Elements tdList = trList.get(0).getElementsByTag("td");
    
        //创建表格
      XWPFTable xwpfTable = doc.createTable(trList.size(), tdList.size());
    
        //设置样式
      TableTools.widthTable(xwpfTable, MiniTableRenderData.WIDTH_A4_FULL, tdList.size());
        TableTools.borderTable(xwpfTable, 4);
    
        //写入表格行和列内容
      Map[][] array = new Map[trList.size()][tdList.size()];
        for (int row = 0; row < trList.size(); row++) {
            Element trElement = trList.get(row);
            Elements tds = trElement.getElementsByTag("td");
            for (int col = 0; col < tds.size(); col++) {
                Element colElement = tds.get(col);
                String colspan = colElement.attr("colspan");
                String rowspan = colElement.attr("rowspan");
                String style = colElement.attr("style");
                StringBuilder styleSB = new StringBuilder();
                if (!StringUtils.isEmpty(colspan)) {
                    int colCount = Integer.parseInt(colspan);
                    for (int i = 0; i < colCount - 1; i++) {
                        array[row][col + i + 1] = new HashMap();
                        array[row][col + i + 1].put("mergeCol", true);
                    }
                }
                if (!StringUtils.isEmpty(rowspan)) {
                    int rowCount = Integer.parseInt(rowspan);
                    for (int i = 0; i < rowCount - 1; i++) {
                        array[row + i + 1][col] = new HashMap();
                        array[row + i + 1][col].put("mergeRow", true);
                    }
                }
                XWPFTableCell tableCell = xwpfTable.getRow(row).getCell(col);
                if (StringUtils.isEmpty(colspan)) {
                    if (col == 0) {
                        if (tableCell.getCTTc().getTcPr() == null) {
                            tableCell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
                        } else {
                            if (tableCell.getCTTc().getTcPr().getHMerge() == null) {
                                tableCell.getCTTc().getTcPr().addNewHMerge().setVal(STMerge.RESTART);
                            } else {
                                tableCell.getCTTc().getTcPr().getHMerge().setVal(STMerge.RESTART);
                            }
                        }
                    } else {
                        if (array[row][col] != null && array[row][col].get("mergeCol") != null && array[row][col].get("mergeCol")) {
                            if (tableCell.getCTTc().getTcPr() == null) {
                                tableCell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
                            } else {
                                if (tableCell.getCTTc().getTcPr().getHMerge() == null) {
                                    tableCell.getCTTc().getTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
                                } else {
                                    tableCell.getCTTc().getTcPr().getHMerge().setVal(STMerge.CONTINUE);
                                }
                            }
                            continue;
                        } else {
                            if (tableCell.getCTTc().getTcPr() == null) {
                                tableCell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
                            } else {
                                if (tableCell.getCTTc().getTcPr().getHMerge() == null) {
                                    tableCell.getCTTc().getTcPr().addNewHMerge().setVal(STMerge.RESTART);
                                } else {
                                    tableCell.getCTTc().getTcPr().getHMerge().setVal(STMerge.RESTART);
                                }
                            }
                        }
                    }
                } else {
                    if (tableCell.getCTTc().getTcPr() == null) {
                        tableCell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
                    } else {
                        if (tableCell.getCTTc().getTcPr().getHMerge() == null) {
                            tableCell.getCTTc().getTcPr().addNewHMerge().setVal(STMerge.RESTART);
                        } else {
                            tableCell.getCTTc().getTcPr().getHMerge().setVal(STMerge.RESTART);
                        }
                    }
                }
                if (StringUtils.isEmpty(rowspan)) {
                    if (array[row][col] != null && array[row][col].get("mergeRow") != null && array[row][col].get("mergeRow")) {
                        if (tableCell.getCTTc().getTcPr() == null) {
                            tableCell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
                        } else {
                            if (tableCell.getCTTc().getTcPr().getVMerge() == null) {
                                tableCell.getCTTc().getTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
                            } else {
                                tableCell.getCTTc().getTcPr().getVMerge().setVal(STMerge.CONTINUE);
                            }
                        }
                        continue;
                    } else {
                        if (tableCell.getCTTc().getTcPr() == null) {
                            tableCell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
                        } else {
                            if (tableCell.getCTTc().getTcPr().getVMerge() == null) {
                                tableCell.getCTTc().getTcPr().addNewVMerge().setVal(STMerge.RESTART);
                            } else {
                                tableCell.getCTTc().getTcPr().getVMerge().setVal(STMerge.RESTART);
                            }
                        }
                    }
                } else {
                    if (tableCell.getCTTc().getTcPr() == null) {
                        tableCell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
                    } else {
                        if (tableCell.getCTTc().getTcPr().getVMerge() == null) {
                            tableCell.getCTTc().getTcPr().addNewVMerge().setVal(STMerge.RESTART);
                        } else {
                            tableCell.getCTTc().getTcPr().getVMerge().setVal(STMerge.RESTART);
                        }
                    }
                }
                tableCell.removeParagraph(0);
                XWPFParagraph paragraph = tableCell.addParagraph();
                paragraph.setStyle(styleSB.toString());
                if (!StringUtils.isEmpty(style) && style.contains("text-align:center")) {
                    paragraph.setAlignment(ParagraphAlignment.CENTER);
                }
                XWPFRun run = paragraph.createRun();
                run.setText(colElement.text());
            }
        }
    }
    
    /**
     * 简化html中的表格dom
     * @author xuwangcheng
     * @date 2019/7/29 18:39
     * @param tableContent tableContent
     * @return {@link String}
     */private static String simplifyTable(String tableContent) {
        if (StringUtils.isEmpty(tableContent)) {
            return null;
        }
        org.jsoup.nodes.Document tableDoc = Jsoup.parse(tableContent);
        Elements trElements = tableDoc.getElementsByTag("tr");
        if (trElements != null) {
            Iterator eleIterator = trElements.iterator();
            Integer rowNum = 0;
            // 针对于colspan操作
      while (eleIterator.hasNext()) {
                rowNum++;
                Element trElement = eleIterator.next();
                //去除所有样式
      trElement.removeAttr("class");
                Elements tdElements = trElement.getElementsByTag("td");
                List tdEleList = covertElements2List(tdElements);
                for (int i = 0; i < tdEleList.size(); i++) {
                    Element curTdElement = tdEleList.get(i);
                    //去除所有样式
      curTdElement.removeAttr("class");
                    Element ele = curTdElement.clone();
                    String colspanValStr = curTdElement.attr("colspan");
                    if (!StringUtils.isEmpty(colspanValStr)) {
                        ele.removeAttr("colspan");
                        Integer colspanVal = Integer.parseInt(colspanValStr);
                        for (int k = 0; k < colspanVal - 1; k++) {
                            curTdElement.after(ele.outerHtml());
                        }
                    }
                }
            }
            // 针对于rowspan操作
      List trEleList = covertElements2List(trElements);
            Element firstTrEle = trElements.first();
            Elements tdElements = firstTrEle.getElementsByTag("td");
            Integer tdCount = tdElements.size();
            //获取该列下所有单元格
      for (int i = 0; i < tdElements.size(); i++) {
                for (Element trElement : trEleList) {
                    List tdElementList = covertElements2List(trElement.getElementsByTag("td"));
                    try {
                        tdElementList.get(i);
                    } catch (Exception e) {
                        continue;
                    }
                    Node curTdNode = tdElementList.get(i);
                    Node cNode = curTdNode.clone();
                    String rowspanValStr = curTdNode.attr("rowspan");
                    if (!StringUtils.isEmpty(rowspanValStr)) {
                        cNode.removeAttr("rowspan");
                        Element nextTrElement = trElement.nextElementSibling();
                        Integer rowspanVal = Integer.parseInt(rowspanValStr);
                        for (int j = 0; j < rowspanVal - 1; j++) {
                            Node tempNode = cNode.clone();
                            List nodeList = new ArrayList();
                            nodeList.add(tempNode);
                            if (j > 0) {
                                nextTrElement = nextTrElement.nextElementSibling();
                            }
                            Integer indexNum = i + 1;
                            if (i == 0) {
                                indexNum = 0;
                            }
                            if (indexNum.equals(tdCount)) {
                                nextTrElement.appendChild(tempNode);
                            } else {
                                nextTrElement.insertChildren(indexNum, nodeList);
                            }
                        }
                    }
                }
            }
        }
        Element tableEle = tableDoc.getElementsByTag("table").first();
        String tableHtml = tableEle.outerHtml();
    
        return tableHtml;
    }
    
    /**
     * 转换Elements为list
     * @author xuwangcheng
     * @date 2019/7/29 18:40
     * @param curElements curElements
     * @return {@link List}
     */private static List covertElements2List(Elements curElements){
        List elementList = new ArrayList();
        Iterator eleIterator = curElements.iterator();
        while(eleIterator.hasNext()){
            Element curlement = eleIterator.next();
            elementList.add(curlement);
        }
        return elementList;
    }
    
    
    以前,我总以为自己是菜鸟,也总想着早起的鸟儿有虫吃。直到有一天我想飞,才愕然的发现自己没有翅膀和羽毛,我竟然是菜虫!早起的虫儿被鸟吃……原来,百足应该厚积薄发!