在Java編程中,如何向Word文檔中添加表格?
注意:需要訪問網址:http://poi.apache.org/download.html , 下載一個Apache POI軟體包。這裏下載最新版本:poi-bin-3.17-20170915.tar.gz解壓並將全部.jar檔導入。
需要導入全部包,如下圖所示 -
以下是向Word文檔中添加表格的程式。
package com.zaixian;
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();
table.setWidth(1000);
// create first row
XWPFTableRow tableRowOne = table.getRow(0);
tableRowOne.getCell(0).setText("1 x 1");
tableRowOne.addNewTableCell().setText("2 x 1");
tableRowOne.addNewTableCell().setText("3 x 1");
// create second row
XWPFTableRow tableRowTwo = table.createRow();
tableRowTwo.getCell(0).setText("1 x 2");
tableRowTwo.getCell(1).setText("2 x 2");
tableRowTwo.getCell(2).setText("3 x 2");
// create third row
XWPFTableRow tableRowThree = table.createRow();
tableRowThree.getCell(0).setText("1 x 3");
tableRowThree.getCell(1).setText("2 x 3");
tableRowThree.getCell(2).setText("3 x 3");
document.write(out);
out.close();
System.out.println("create_table.docx written successully");
}
}
執行上面示例代碼,得到以下結果 -
create_table.docx written successully
生成的World文檔,得到以下結果 -
上一篇:
Java POI Word
下一篇:
Java OpenCV