Page 1 of 1

Unable to delete table from word document using docx4j

PostPosted: Sun Sep 02, 2018 2:45 am
by tahir
My word document has two tables and I am trying to delete last table with following code:
Code: Select all
public static void removeTable() throws Docx4JException, JAXBException {
    File doc = new File("D:\\Hello.docx");
    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(doc);
    MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart();
    String xpath = "//w:tbl";
    List<Object> list = mainDocumentPart.getJAXBNodesViaXPath(xpath, false);

    if(list.size()==2){
        Tbl tbl = (Tbl) XmlUtils.unwrap(list.get(list.size()-1));
        mainDocumentPart.getContent().remove(tbl.getParent());
        wordMLPackage.save(new java.io.File("D:\\Hello.docx"));
        System.out.println(list.size());
    }
}

But nothing is happening to my document.
Then I used following code:
Code: Select all
public class RemoveLastTable {

    public static void main(String[] args) throws Docx4JException {
        File doc = new File("d:\\tmp\\tables.docx");
        WordprocessingMLPackage pkg = WordprocessingMLPackage.load(doc);
        removeLastTable(pkg, "d:\\tmp\\tables_updated.docx");

    }

    public static void removeLastTable(WordprocessingMLPackage wordMLPackage, String outFile) throws Docx4JException {

        Body body = wordMLPackage.getMainDocumentPart().getContents().getBody();
        List<Object> tables = getAllElementFromObject(body, Tbl.class);
        int indexTableToRemove = tables.size() - 1;
        Tbl tableToRemove = (Tbl) tables.get(indexTableToRemove);
        body.getContent().remove(tableToRemove.getParent());
        wordMLPackage.save(new File(outFile));
    }

    private static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) {
        List<Object> result = new ArrayList<>();
        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;
    }
}

But table is still there in my document. Can anybody help me in this regard? My word (docx) file is also attached. It has 02 tables without borders. I want to delete last table. Thanks

Re: Unable to delete table from word document using docx4j

PostPosted: Sun Sep 02, 2018 6:47 pm
by jason
Answered at your cross post https://stackoverflow.com/a/52134975/1031689

Please don't cross post, since if only one of your posts is answered, it looks like nobody cares :-)