2017-09-21 28 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