您的位置:首页 > 其它

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

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

用到的POI对象是:XWPFDocument

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

OPCPackage opcPackage = POIXMLDocument.openPackage(wordFilePath);

        XWPFDocument doc = new XWPFDocument(opcPackage);

        List<XWPFTable> list = doc.getTables();

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

XWPFTableRow crtRow = tb.createRow();

            List<XWPFTableCell> 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<XWPFParagraph> paragraphs = document.getParagraphsIterator();

            while (paragraphs.hasNext()) {

                XWPFParagraph paragraph = (XWPFParagraph) paragraphs.next();

                Set<Entry<String, String>> set = map.entrySet();

                for (Map.Entry<String, String> 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<XWPFRun> 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 Word
相关文章推荐