Reputation: 147
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");
Upvotes: 2
Views: 4645
Reputation: 61945
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");
FileOutputStream out = new FileOutputStream("WordTextAfterTableNew.docx");
document.write(out);
out.close();
document.close();
}
}
Upvotes: 3
Reputation: 173
this works for me:
tablasolicitantecargo = tablafiladoss.getTable();
org.apache.xmlbeans.XmlCursor cursor = tablasolicitantecargo.getCTTbl().newCursor();
cursor.toEndToken();
while(cursor.toNextToken() != org.apache.xmlbeans.XmlCursor.TokenType.START);
XWPFParagraph newParagraph = requisicionesaprobadas.insertNewParagraph(cursor);
@SuppressWarnings("unused")
XWPFRun run = newParagraph.createRun();
Upvotes: 0