个性化阅读
专注于IT技术分析

apache poi word表格

点击下载

本文概述

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

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

Apache POI 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()它用于获取表中的行数。

Apache POI Word表示例

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("srcmini.docx"))){
	    	  // Creating Table
	    	  XWPFTable tab = document.createTable();
	    	  XWPFTableRow row = tab.getRow(0); // First row
	    	  // Columns
	    	  row.getCell(0).setText("Sl. No.");
	          row.addNewTableCell().setText("Name");
	          row.addNewTableCell().setText("Email");
	          row = tab.createRow(); // Second Row
	          row.getCell(0).setText("1.");
	          row.getCell(1).setText("Irfan");
	          row.getCell(2).setText("irfan@gmail.com");
	          row = tab.createRow(); // Third Row
	          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);
	      }
	   }
}

输出:

赞(0)
未经允许不得转载:srcmini » apache poi word表格

评论 抢沙发

评论前必须登录!