用POI在word07模板文件中创建表格,修改内容等操作

  最近做项目时,需要利用POI技术,在word文档中写表格,但是网上几乎搜索不到相关资料,经过2天的研究,终于实现了功能。

用到的POI对象是:XWPFDocument

读取模板文件获取所有的table:

OPCPackage opcPackage = POIXMLDocument.openPackage(wordFilePath);
        XWPFDocument doc = new XWPFDocument(opcPackage);
        List list = doc.getTables();

对表格增加新的一行,并设置数据:

XWPFTableRow crtRow = tb.createRow();
            List cells = crtRow.getTableCells();
            for (int j = 0; j < cells.size(); j++) {
                cells.get(j).removeParagraph(0);
                cells.get(j).setText(map.get(j));
                // cells.get(j).setVerticalAlignment(XWPFVertAlign.BOTH);
                LOGGER.debug("insert into table value:" + map.get(j));
            }

如需删除行:

                  tb.getCTTbl().removeTr(row);
                // tb.removeRow(row);  API删除行有点问题,我就直接用源码的一部分(上面一句话)即可。

文字的替换原则 :先删后加


            Iterator paragraphs = document.getParagraphsIterator();
            while (paragraphs.hasNext()) {

                XWPFParagraph paragraph = (XWPFParagraph) paragraphs.next();
                Set> set = map.entrySet();

                for (Map.Entry key : set) {
                    String text = "";
                    if (paragraph.getParagraphText().indexOf(key.getKey()) != -1) {

                        PositionInParagraph positionInParagraph = new PositionInParagraph();

                        TextSegement textSegement = SearchText.searchTextOfParagraph(paragraph.getCTP(), key.getKey(),
                                positionInParagraph);

                        text = paragraph.getText(textSegement).replace(key.getKey(), key.getValue());

                        List paragraphRuns = paragraph.getRuns();

                        for (int i = textSegement.getEndRun(); i > textSegement.getBeginRun(); i--) {
                            paragraph.removeRun(i);
                        }

                        XWPFRun paragraphRun = paragraphRuns.get(textSegement.getBeginRun());
                        CTR ctr = paragraphRun.getCTR();
                        for (int i = ctr.sizeOfTArray() - 1; i >= 0; i--) {
                            ctr.removeT(i);
                        }
                        paragraphRun.setText(text);
                    }
                }
            }
       

我修改了API搜索文本方法:searchText  为  SearchText.searchTextOfParagraph(CTP paragraph, String searched, PositionInParagraph startPos)

paragraph.getRList()改为paragraph.getRArray()

你可能感兴趣的:(用POI在word07模板文件中创建表格,修改内容等操作)