0
votes

I have word document (it is docx and xml based), I want to find a table and populate it programmatically. I am using Apache POI, XWPF API.

Is there a way to access XWPF elements by their id?

How can I create uniqueness between XWPF elements then alter using java?

Thanks

1
From what ID are you talking about? How will you set those ID in Word? A Wordtable may have Title in Table Properties - Alt Text. Is this meant?Axel Richter
Hi Axel, yes AFAIK there is no id. But I would like to understand how other people are using it. Alt text is a good solution actually for tables. But I am curious how other people using XWPF interface.ozkolonur
There is not a general ordering criterion of elements in a Worddocument except their occurrence from top to down. So in general case iterate over all IBodyElements, determine what BodyElementType you got and then do with that element what you need to do. In special cases the requirement must be clear. For example you could replace place holder texts or filling form fields or looking for headings/bookmarks/captions/alt-texts/... to determine elements. But for this the requirement must also be clear for the author of the Word document since he must write those things into the document.Axel Richter

1 Answers

1
votes

What I have implemented is a find replace feature(from here);

In my template docx file I am using "id like texts", __heading1__, __subjectname__, Then replacing with them using code below. For tables @axel-richters solution may be suitable.

private void findReplace(String a, String b, CustomXWPFDocument document){
    for (XWPFParagraph p : document.getParagraphs()) {
        List<XWPFRun> runs = p.getRuns();
        if (runs != null) {
            for (XWPFRun r : runs) {
                String text = r.getText(0);
                if (text != null && text.contains(a)) {
                    text = text.replace(a, b);
                    r.setText(text, 0);
                }
            }
        }
    }
}