Output:
I want to fill the 2nd and 4th cell of this table. what I have tried:
//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();
}
I also tried two or more similar ways to accomplish this but no luck. Why can't we just do cell(1).setText("Hello World")
? (This is not working)
What is the way to do this? Thanks
I cannot confirm that XWPFTableCell.setText does not work. For me it works using current apache poi 4.1.2
.
Let's have a complete example:
My WordTableExample.docx
looks like this:
Then this code:
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();
}
}
produces this resulting WordTableExampleNew.docx
: