Apache POI单词在表格后添加文字的最佳方式
问题描述:
在表格后添加文字的最佳或简短方式是什么?不在桌上,但在之后。 该表位于docx文件中。Apache POI单词在表格后添加文字的最佳方式
因此,例如:
- TEXTA
- TEXTB
- 表
- textC
- textD
我想补充的表和textC之间的一些文字。 结果:
- TEXTA
- TEXTB
- 表
- 插入新的文本
- textC
- textD
我尝试下面的代码,但它的表之前的插入后不。
XmlCursor cursor = table.getCTTbl().newCursor();
XWPFParagraph newParagraph = doc.insertNewParagraph(cursor);
XWPFRun run = newParagraph.createRun();
run.setText("inserted new text");
答
使用XmlCursor的方法是正确的。阅读更多关于这个XmlCursor
和链接文档中的方法。
所以我们需要跳到CTTbl
的末尾,然后找到下一个元素的开始标签。
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();
}
}
+0
谢谢你的帮助。 – Zaosz
在表格后面创建'XWPFParagraph',然后'XWPFRun'包含本段中的文本。 –
好的,但我怎样才能设置XWPFParagraph的位置?我试过这个:XmlCursor cursor = table.getCTTbl()。newCursor()但是表格的前面位置。 – Zaosz
请编辑您的问题并显示您正在使用的代码。还要详细解释你在做什么。桌子从哪里来?你怎么弄桌子? –