[英]Enter text to a Table Cell in a Doc file using apache poi in java
Output:
我想填寫此表的第二個和第四個單元格。 我嘗試過的:
//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")
? (這不起作用)
這樣做的方法是什么? 謝謝
我無法確認XWPFTableCell.setText不起作用。 對我來說,它使用當前的apache poi 4.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
:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.