簡體   English   中英

Apache POI word 在表格后添加文本的最佳方式

[英]Apache POI word best way to add text after table

在表格后添加文本的最佳或簡短方法是什么? 不在桌子上,而是在后面。 該表位於 docx 文件中。

所以,例如:

  • 文本A
  • 文本B
  • 文本C
  • 文本D

我想在 Table 和 textC 之間添加一些文本。 結果:

  • 文本A
  • 文本B
  • 插入新文本
  • 文本C
  • 文本D

我嘗試了以下代碼,但它是在表之前而不是之后插入的。

 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();
 }
}

我使用了下面的代碼並修復了

在此處輸入圖片說明

這對我有用:

                 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(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM