fusulbashi
fusulbashi

Reputation: 1

Apache Poi Word Table, information about the Alt Text

How to get the Alt Text from a Table in Word, e.g. Title or Description. All the Information, that I found had the context, Text, Width, Style etc. to read or modify.

My goal is to identify certain Tables in a Template, so I can modify them.

Upvotes: 0

Views: 1385

Answers (2)

Baked Inhalf
Baked Inhalf

Reputation: 3735

In Word you can set the table caption to something unique, and then get the table in xml:

String tableXML = mytable.getCTTbl();

To extract the table caption:

String[] xml = tableXML.split(System.lineSeparator());
String caption = null;
for (String x : xml)
{
    if (x.contains("w:tblCaption"))
    {
        caption = x.split("w:val=")[1].replace("/>", "");
        caption = caption.replace("\"", "");
    }
}

Upvotes: 0

jmarkmurphy
jmarkmurphy

Reputation: 11483

I am going to make some assumptions here. First that you are talking about the docx format, and second that by "Alt Text" you mean a caption.

A caption is just a paragraph that either precedes, or follows a table. It will have a style of Caption, a run with some text like Table, and probably includes a simple field SEQ Table. That would be the default Table caption, but it could be just a run with a name like Department Heads. The key is the style name. Word uses standard style names to calculate other things as well such as TOC.

Note: in Word, you cannot modify a caption by selecting a table, and clicking a menu option. It isn't really linked in any meaningful way. You have to modify the paragraph.

So to find a caption, you need to look in the Document elements list XWPFDocument.getBodyElements(), and find each paragraph with a style of Caption. Once you have found the one you want, then you can either look at the element immediately above or below to find the table. Your search will be easier if you can know that captions are all above or all below the tables.

So to retrieve the table following a specific named caption I would try something like this:

public XWPFTable FindTable(String name) {
    boolean foundTable = false;
    XWPFParagraph p;
    for (IBodyElement elem : doc.getBodyElements()) {
        switch (elem.getElementType()) {
        case PARAGRAPH:
            foundTable = false;
            p = (XWPFParagraph) elem;
            if (p.getStyle() == "Caption" && p.getText() == name) {
                foundTable = true;
            }
            break;
        case TABLE:
            if (foundTable) {
                return (XWPFTable) elem;
            }
            break;
        case CONTENTCONTROL:
            foundTable = false;
            break;
        default:
            foundTable = false;
            break;
        }
    }

    return null;
}

Upvotes: 1

Related Questions