360SDN.COM

首页/Java/列表

利用POI3.7 实现对openxmlformats(docx)格式模板文档的替换

来源:  2017-10-24 13:41:40    评论:0点击:



网络中对POI XWPF 相关编程内容描述较少,而POI HWPF对word2003以下文档处理能力有限,在GOOGLE后,看了对word中表格文字处理的相关博文后,深受启发,明确了处理思路,就是对替换的内容,要先删除,后添加。

主要实现代码如下:

    
    public void searchAndReplace(XWPFDocument document, Map map) {
        try {
            Iterator 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 = "";
                    while (paragraph.getParagraphText().indexOf(key.getKey()) != -1) {
                        PositionInParagraph positionInParagraph = new PositionInParagraph();
                        TextSegement textSegement = 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);
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("searchAndReplace:" + e.getMessage());
        }
    }

 

代码参考原XWPFParagraph 中searchText方法,对paragraph.getTList()方法重新修改为paragraph.getRArray(),以searchTextOfParagraph方法进行替代,并调用CTR 中removeT(i)清空原文字,再重新赋值(XWPFRun 的setText方法是在原文后追加文本)。
为您推荐

友情链接 |九搜汽车网 |手机ok生活信息网|ok生活信息网|ok微生活
 Powered by www.360SDN.COM   京ICP备11022651号-4 © 2012-2016 版权