- Apache POI Word 教程
- Apache POI Word - 首頁
- Apache POI Word - 概述
- Apache POI Word - 安裝
- Apache POI Word - 核心類
- Apache POI Word - 文件
- Apache POI Word - 段落
- Apache POI Word - 邊框
- Apache POI Word - 表格
- Apache POI Word - 字型和對齊
- Apache POI Word - 文字提取
- Apache POI Word 資源
- Apache POI Word - 快速指南
- Apache POI Word - 實用資源
- Apache POI Word - 討論
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 檔案如下所示-
廣告