无涯教程-POI Word - 创建表格

121 阅读1分钟

要在Word文档中创建表,无涯教程可以使用 org.apache.poi.xwpf.usermodel.XWPFTable 包中的 XWPFTable 类。 Apache POI又添加了一个 XWPFTableRow 类用于创建行。

看到,下面使用Java程序在Word文档中创建了一个表。

XWPFTable方法

以下是处理文档中表格的常用方法。

方法 说明
public void addNewCol() 它将为此表中的每一行添加一个新列。
public void addRow(XWPFTableRow row) 它将在表中添加一个新行。
public XWPFTableRow createRow() 它会创建一个新的XWPFTableRow对象,该对象的单元格数量与当时定义的列数一样。
public java.lang.String getText() 它用于提取单元格中的文本。
public void setWidth(int width) 用于设置宽度。
public int getNumberOfRows() 它用于获取表中的行数。

XWPFTable示例

package poiexample;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
public class TableExample {
	public static void main(String[] args)throws Exception {
	      XWPFDocument document= new XWPFDocument();
	      try(FileOutputStream out = new FileOutputStream(new File("Learnfk.docx"))){
	    	 //创建表
	    	  XWPFTable tab = document.createTable();
	    	  XWPFTableRow row = tab.getRow(0);//第一行
	    	 //列
	    	  row.getCell(0).setText("Sl. No.");
	          row.addNewTableCell().setText("Name");
	          row.addNewTableCell().setText("Email");
	          row = tab.createRow();//第二行
	          row.getCell(0).setText("1.");
	          row.getCell(1).setText("Irfan");
	          row.getCell(2).setText("irfan@gmail.com");
	          row = tab.createRow();//第三行
	          row.getCell(0).setText("2.");
	          row.getCell(1).setText("Mohan");
	          row.getCell(2).setText("mohan@gmail.com");	  
	          document.write(out);
	      }catch(Exception e) {
	    	  System.out.println(e);
	      }
	   }
}

输出:

Apache POI Word Table

参考链接

www.learnfk.com/apache-poi-…