- Java 程式設計示例
- 示例 - 主頁
- 示例 - 環境
- 示例 - 字串
- 示例 - 陣列
- 示例 - 日期和時間
- 示例 - 方法
- 示例 - 檔案
- 示例 - 目錄
- 示例 - 異常
- 示例 - 資料結構
- 示例 - 集合
- 示例 - 網路
- 示例 - 多執行緒
- 示例 - 小程式
- 示例 - 簡單 GUI
- 示例 - JDBC
- 示例 - 正則表示式
- 示例 - Apache PDF Box
- 示例 - Apache POI PPT
- 示例 - Apache POI Excel
- 示例 - Apache POI Word
- 示例 - OpenCV
- 示例 - Apache Tika
- 示例 - iText
- Java 教程
- Java - 教程
- Java 有用資源
- Java - 快速指南
- Java - 有用資源
如何利用 Java 向 Word 文件中新增表格
問題描述
如何利用 Java 向 Word 文件中新增表格。
解決方案
以下是利用 Java 向 Word 文件中新增表格的程式。
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 TablesToWord {
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");
}
}
輸出
java_apache_poi_word
廣告