使用java中的ApachePOI向文档文件中的表单元格输入文本

使用java中的ApachePOI向文档文件中的表单元格输入文本,java,apache-poi,doc,Java,Apache Poi,Doc,输出: 我想填这张表的第二和第四个单元格。 我所尝试的: //got this from an answer here. XWPFTable table = doc.getTableArray(0); XWPFTableRow oldRow = table.getRow(1); //the cell is in the second row XWPFParagraph paragraph = oldRow.getCell(1).addParagraph(); X

输出:

我想填这张表的第二和第四个单元格。 我所尝试的:

//got this from an answer here.
  XWPFTable table = doc.getTableArray(0);
  XWPFTableRow oldRow = table.getRow(1);         //the cell is in the second row
  XWPFParagraph paragraph = oldRow.getCell(1).addParagraph();
  XWPFParagraph paragraph1 = oldRow.getCell(3).addParagraph();
  setRun(paragraph.createRun() , "Times New Roman" , 10, "2b5079" , "I want to enter this!" , true, false); //for 2nd cell
  setRun(paragraph1.createRun() , "Times New Roman" , 10, "2b5079" , "I want to enter this too!" , true, false);//for 4th cell

private void setRun (XWPFRun run , String fontFamily , int fontSize , String colorRGB , String text , boolean bold , boolean addBreak) {
        run.setFontFamily(fontFamily);
        run.setFontSize(fontSize);
        run.setColor(colorRGB);
        run.setText(text);
        run.setBold(bold);
        if (addBreak)
            run.addBreak();
    }
我也尝试了两种或更多类似的方法来实现这一点,但没有运气。为什么我们不能只做
cell(1).setText(“Hello World”)
?(这不起作用)

这样做的方法是什么? 谢谢

我不能确认这不起作用。对我来说,它使用当前的ApachePOI4.1.2工作

让我们举一个完整的例子:

我的
WordTableExample.docx
如下所示:

然后这个代码:

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

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

public class WordFillTableCells {

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

  XWPFDocument document = new XWPFDocument(new FileInputStream("./WordTableExample.docx"));

  XWPFTable table = document.getTableArray(0);
  XWPFTableRow row = table.getRow(1);
  XWPFTableCell cell = row.getCell(1);
  cell.setText("New content of cell row 2 cell 2.");

  cell = row.getCell(3);
  cell.setText("New content of cell row 2 cell 4.");

  FileOutputStream out = new FileOutputStream("./WordTableExampleNew.docx");
  document.write(out);
  out.close();
  document.close();
 }
}
生成此结果
WordTableExampleNew.docx