codecamp

Apache POI Word - 表格

在本章中,您将学习如何在文档中创建数据表。 您可以使用 XWPFTable 类创建表数据。 将每个添加到表格中,并将单元格添加到,您将获得表格数据。

创建表

以下代码用于在文档中创建表:

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 CreateTable 
{
   public static void main(String[] args)throws Exception 
   {
   //Blank Document
   XWPFDocument document= new XWPFDocument();
        
   //Write the Document in file system
   FileOutputStream out = new FileOutputStream(
   new File("create_table.docx"));
        
   //create table
   XWPFTable table = document.createTable();
   //create first row
   XWPFTableRow tableRowOne = table.getRow(0);
   tableRowOne.getCell(0).setText("col one, row one");
   tableRowOne.addNewTableCell().setText("col two, row one");
   tableRowOne.addNewTableCell().setText("col three, row one");
   //create second row
   XWPFTableRow tableRowTwo = table.createRow();
   tableRowTwo.getCell(0).setText("col one, row two");
   tableRowTwo.getCell(1).setText("col two, row two");
   tableRowTwo.getCell(2).setText("col three, row two");
   //create third row
   XWPFTableRow tableRowThree = table.createRow();
   tableRowThree.getCell(0).setText("col one, row three");
   tableRowThree.getCell(1).setText("col two, row three");
   tableRowThree.getCell(2).setText("col three, row three");
	
   document.write(out);
   out.close();
   System.out.println("create_table.docx written successully");
   }
}

将上述代码保存在名为 CreateTable.java的文件中。从命令提示符处编译并执行它,如下所示:

$javac CreateTable.java
$java CreateTable

它将在当前目录中生成名为 createtable.docx 的Word文件,并在命令提示符下显示以下输出:

createtable.docx written successfully

createtable.docx 文件如下所示:


Apache POI Word - 边框
Apache POI Word - 字体样式和对齐方式
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }