0

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

ozkolonur
  • 1,430
  • 1
  • 15
  • 22
  • 1
    From what `ID` are you talking about? How will you set those `ID` in Word? A `Word`table may have `Title` in [Table Properties - Alt Text](https://support.office.com/en-us/article/Set-or-change-table-properties-3237de89-b287-4379-8e0c-86d94873b2e0#__toc5). Is this meant? – Axel Richter Jul 03 '17 at 12:42
  • 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 Jul 03 '17 at 13:00
  • There is not a general ordering criterion of elements in a `Word`document except their occurrence from top to down. So in general case iterate over all `IBodyElement`s, 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 Jul 03 '17 at 14:21

1 Answers1

1

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);
                }
            }
        }
    }
}
ozkolonur
  • 1,430
  • 1
  • 15
  • 22