- 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