0
votes

I am trying to search a string in docx and replace with some other text using java apache poi but it is replacing randomly getting error as arrayIndexoutofbound Exception in line

"declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//w:ffData/w:name/@w:val")[0];

public class WordReplaceTextInFormFields {

private static void replaceFormFieldText(XWPFDocument document, String ffname, String text) {
    boolean foundformfield = false;
    for (XWPFParagraph paragraph : document.getParagraphs()) {
        for (XWPFRun run : paragraph.getRuns()) {
            XmlCursor cursor = run.getCTR().newCursor();
            cursor.selectPath(
                    "declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//w:fldChar/@w:fldCharType");
            while (cursor.hasNextSelection()) {
                cursor.toNextSelection();
                XmlObject obj = cursor.getObject();
                if ("begin".equals(((SimpleValue) obj).getStringValue())) {
                    cursor.toParent();
                    obj = cursor.getObject();
                    obj = obj.selectPath(
                            "declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//w:ffData/w:name/@w:val")[0];
                    if (ffname.equals(((SimpleValue) obj).getStringValue())) {
                        foundformfield = true;
                    } else {
                        foundformfield = false;
                    }
                } else if ("end".equals(((SimpleValue) obj).getStringValue())) {
                    if (foundformfield)
                        return;
                    foundformfield = false;
                }
            }
            if (foundformfield && run.getCTR().getTList().size() > 0) {
                run.getCTR().getTList().get(0).setStringValue(text);
                // System.out.println(run.getCTR());
            }
        }
    }
}

public static void main(String[] args) throws Exception {

    XWPFDocument document = new XWPFDocument(new FileInputStream("WordTemplate.docx"));

    replaceFormFieldText(document, "Text1", "Моя Компания");
    replaceFormFieldText(document, "Text2", "Аксель Джоачимович Рихтер");
    replaceFormFieldText(document, "Text3", "Доверенность");

    document.write(new FileOutputStream("WordReplaceTextInFormFields.docx"));
    document.close();
}
}

it misses some string, it not replaces entire document..please help with sample code

1

1 Answers

0
votes

I do something similar in my project at https://github.com/centic9/poi-mail-merge which provides a general mail-merge functionality based on POI. It is using a bit different functionality from XmlBeans which replaces strings in the full XML-content of the document instead of each paragraph separately.

    private static void appendBody(CTBody src, String append, boolean first) throws XmlException {
        XmlOptions optionsOuter = new XmlOptions();
        optionsOuter.setSaveOuter();
        String srcString = src.xmlText();
        String prefix = srcString.substring(0,srcString.indexOf(">")+1);

        final String mainPart;
        // exclude template itself in first appending
        if(first) {
            mainPart = "";
        } else {
            mainPart = srcString.substring(srcString.indexOf(">")+1,srcString.lastIndexOf("<"));
        }

        String suffix = srcString.substring( srcString.lastIndexOf("<") );
        String addPart = append.substring(append.indexOf(">") + 1, append.lastIndexOf("<"));
        CTBody makeBody = CTBody.Factory.parse(prefix+mainPart+addPart+suffix);
        src.set(makeBody);
    }
}

See line 132 in MailMerge.java