在内容之间插入XWPFTable [英] Inserting XWPFTable in between contents

查看:627
本文介绍了在内容之间插入XWPFTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在某些内容之间插入XWPFTable.文件是内容固定的,文件作为输入.我需要在特定字段中插入表格.

HI I would like to insert a XWPFTable in between some contents. The file is content is fixed and file is taken as input. I need the table to be inserted in the specific field.

像这样:

Stack Overflow是一个私有网站,是Stack Exchange Network的旗舰网站,由Jeff Atwood和Joel Spolsky于2008年创建.这是桌子.

Stack Overflow is a privately held website, the flagship site of the Stack Exchange Network, created in 2008 by Jeff Atwood and Joel Spolsky. Here is the table.

内容继续.它被创建为对早期问答网站(例如Experts-Exchange)的更开放的替代方式.

The contents continue.It was created to be a more open alternative to earlier question and answer sites such as Experts-Exchange.

谢谢

我编写的代码

public static void main(String[] args) throws IOException {
        XWPFDocument document = new XWPFDocument(new FileInputStream(new File("input.docx")));
        FileOutputStream out = new FileOutputStream(new File("output.docx"));
        XmlCursor cursor = null;
         List<IBodyElement> elements = document.getBodyElements();
         for (int n = 0; n < elements.size(); n++) {
             IBodyElement element = elements.get(n);
             if (element instanceof XWPFParagraph) {
                 XWPFParagraph p1 = (XWPFParagraph) element;
                 List<XWPFRun> runList = p1.getRuns();
                 StringBuilder sb = new StringBuilder();
                 for (XWPFRun run : runList)
                     sb.append(run.getText(0));
                 if (sb.toString().contains("Text after which table should be created")) {
                      cursor= p1.getCTP().newCursor();
                      break;
             }
         }
    } 
         XWPFParagraph p = document.insertNewParagraph(cursor);
         XWPFTable table = p.getBody().insertNewTbl(cursor);
         XWPFTableRow tableRowOne = table.createRow();

        //other codes for generating the table  

创建行时出现空指针异常.

I am getting null pointer exception on creating the row.

推荐答案

已测试.我的猜想是对的. XWPFParagraph p = document.insertNewParagraph(cursor);之后,光标在代码中的错误位置.所以XWPFTable table = p.getBody().insertNewTbl(cursor);不能插入,然后是null.

Have tested now. My suspicion was right. The cursor was on the wrong place in your code after XWPFParagraph p = document.insertNewParagraph(cursor);. So the XWPFTable table = p.getBody().insertNewTbl(cursor); could not be inserted and was null then.

但是还有其他问题.如果找到了文本,我们将在表格的后段中.因此,我们需要将光标移动到下一段.但是,如果没有下一段,该怎么办?然后需要创建一个新段落.幸运的是,

But there are further problems. If the text was found, we are in the paragraph after which the table shall be placed. So we need moving the cursor to the next paragraph. But what if there is not a next paragraph? Then a new paragraph needs to be created. Fortunately the XmlCursor.toNextSibling flags if it was successful.

示例:

模板:

代码:

import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.*;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;

import org.apache.xmlbeans.XmlCursor;
import java.math.BigInteger;


public class WordInsertTableInBody {

 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument(new FileInputStream("WordTableExample.docx"));
  XmlCursor cursor = null;
  XWPFParagraph paragraph = null; 
  XWPFRun run = null; 

  boolean foundTablePosition = false;
  boolean thereWasParagraphAfter = false;
  for (IBodyElement element : document.getBodyElements()) {
   if (element instanceof XWPFParagraph) {
    paragraph = (XWPFParagraph) element;
    StringBuilder sb = new StringBuilder();
    for (XWPFRun irun : paragraph.getRuns()) {
     sb.append(irun.getText(0));
System.out.println(sb);
     if (sb.toString().contains("Text after which table should be created")) {
      cursor= paragraph.getCTP().newCursor();
      thereWasParagraphAfter = cursor.toNextSibling(); // move cursor to next paragraph 
       //because the table shall be **after** that paragraph
       //thereWasParagraphAfter is true if there is a next paragraph, else false
      foundTablePosition = true;
     }
    }
   }
   if (foundTablePosition) break;
  } 

  if (cursor != null) {
   if (thereWasParagraphAfter) {
    paragraph = document.insertNewParagraph(cursor);
   } else {
    paragraph = document.createParagraph();
   }
   cursor = paragraph.getCTP().newCursor();
   XWPFTable table = document.insertNewTbl(cursor);
   XWPFTableRow row = table.getRow(0); if (row == null) row = table.createRow();
   int twipsPerInch =  1440;
   table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(1*1440));
   for (int col = 1 ; col < 4; col++) {
    table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(1*1440));
   }
   for (int i = 0; i < 4; i++) {
    XWPFTableCell cell = row.getCell(i); if (cell == null) cell = row.createCell();
    CTTblWidth tblWidth = cell.getCTTc().addNewTcPr().addNewTcW();
    tblWidth.setW(BigInteger.valueOf(1 * twipsPerInch));
    tblWidth.setType(STTblWidth.DXA);
    paragraph = cell.getParagraphs().get(0);
    run = paragraph.createRun();
    run.setText("Table Cell " + i);
   }
  }

  FileOutputStream out = new FileOutputStream("WordTableExampleNew.docx");
  document.write(out);
  out.close();
  document.close();
 }
}

结果:

这篇关于在内容之间插入XWPFTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆