java - 使用 java 中的 apache poi 在 Doc 文件中的表格单元格中输入文本
问题描述
输出:
我想填写此表的第 2 和第 4 个单元格。我尝试过的:
//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不起作用。对我来说,它使用 current 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
:
推荐阅读
- php - 组合数组并为每个数组添加键
- json - 需要使用邮递员从响应中提取 JSON 值有没有办法做到这一点
- python-3.x - Yocto:为 SciKit-learn 创建配方
- sql - 初学者:LEFT JOIN 不该做什么?
- pandas - 熊猫数据框中两个不同长度的值之间的差异
- python-3.x - 我无法与 Kibana 服务器通信
- json - 使用 ExtJs 在 asp.net MVC 和 WebApi 应用程序中为 MacO 上的 Safari 序列化日期
- java - 如何在 Aerospike Spring Data 中使用 CAS 感知策略保存文档
- batch-file - 删除字母和特殊情况。仅显示特定行文本的数量
- android - 如何为移动设备开发微应用程序(ios和android)