What is the best or short way to add text after table? Not in table but after. The table is in the docx file.
So, example:
I want to add some text between the Table and textC. Result:
I tried following code but it's insert before the table not after.
XmlCursor cursor = table.getCTTbl().newCursor();
XWPFParagraph newParagraph = doc.insertNewParagraph(cursor);
XWPFRun run = newParagraph.createRun();
run.setText("inserted new text");
The approach using a XmlCursor is correct. Read more about this XmlCursor
and it's methods in the linked document.
So we need jumping to the end of the CTTbl
and then finding the next element's start tag.
import java.io.FileOutputStream;
import java.io.FileInputStream;
import org.apache.poi.xwpf.usermodel.*;
public class WordTextAfterTable {
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument(new FileInputStream("WordTextAfterTable.docx"));
XWPFTable table = document.getTableArray(0);
org.apache.xmlbeans.XmlCursor cursor = table.getCTTbl().newCursor();
cursor.toEndToken(); //now we are at end of the CTTbl
//there always must be a next start token. Either a p or at least sectPr.
while(cursor.toNextToken() != org.apache.xmlbeans.XmlCursor.TokenType.START);
XWPFParagraph newParagraph = document.insertNewParagraph(cursor);
XWPFRun run = newParagraph.createRun();
run.setText("inserted new text");
document.write(new FileOutputStream("WordTextAfterTableNew.docx"));
document.close();
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments