Page 1 of 1

remove table from document

PostPosted: Fri Mar 01, 2013 2:02 am
by fachhoch
I am trying to remove a table from my document . First I find the table then wordMLPackage.getMainDocumentPart().getContent().remove(findingTable);

this does not remove table.

if not from the wordMLPackage.getMainDocumentPart().getContent() ? from where should I remove the table.

Attached my docx and java file.

Re: remove table from document

PostPosted: Fri Mar 01, 2013 8:33 am
by jason
That's the right idea. However, your table might be wrapped in a JAXBElement (so its the JAXBElement in the list, rather than the table itself).

See http://stackoverflow.com/questions/1473 ... ith-docx4j for one way of dealing with this.

Re: remove table from document

PostPosted: Fri Jun 05, 2015 12:04 pm
by julien_ncit
Hi guys,

To remove tables, this code works as well :

Code: Select all
public void removeTable(int indexTableToRemove) {
        if (indexTableToRemove < 0)
            throw new InvalidParameterException("indexTableToRemove is negative !")

        Body body = this.wordMLPackage.getMainDocumentPart().getJaxbElement().getBody()
        List<Object> listeTables = getAllElementFromObject(body, Tbl.class)
        Tbl tableToRemove = listeTables[indexTableToRemove]

        if (indexTableToRemove > listeTables.size())
            throw new InvalidParameterException("indexTableToRemove exceed the number of tables contain in the document !")

        body.getContent().remove(tableToRemove.getParent())
    }

private static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) {
        List<Object> result = new ArrayList<Object>();
        if (obj instanceof JAXBElement) obj = ((JAXBElement<?>) obj).getValue();

        if (obj.getClass().equals(toSearch)) {
            result.add(obj);
        }

        if (obj instanceof ContentAccessor) {
            List<?> children = ((ContentAccessor) obj).getContent();
            for (Object child : children) {
                result.addAll(getAllElementFromObject(child, toSearch));
            }

        }
        return result;
    }