在本章中,您將學(xué)習(xí)如何在文檔中創(chuàng)建數(shù)據(jù)表。 您可以使用 XWPFTable 類創(chuàng)建表數(shù)據(jù)。 將每個行添加到表格中,并將單元格添加到行,您將獲得表格數(shù)據(jù)。
以下代碼用于在文檔中創(chuàng)建表:
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的文件中。從命令提示符處編譯并執(zhí)行它,如下所示:
$javac CreateTable.java $java CreateTable
它將在當(dāng)前目錄中生成名為 createtable.docx 的Word文件,并在命令提示符下顯示以下輸出:
createtable.docx written successfully
createtable.docx 文件如下所示:
更多建議: