2017-09-21 27 views
1

在表格后添加文字的最佳或简短方式是什么?不在桌上,但在之后。 该表位于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"); 
+0

在表格后面创建'XWPFParagraph',然后'XWPFRun'包含本段中的文本。 –

+0

好的,但我怎样才能设置XWPFParagraph的位置?我试过这个:XmlCursor cursor = table.getCTTbl()。newCursor()但是表格的前面位置。 – Zaosz

+0

请编辑您的问题并显示您正在使用的代码。还要详细解释你在做什么。桌子从哪里来?你怎么弄桌子? –

回答

1

使用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