ตัวอย่างโคด
package com.java.poi.word;
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 CreateTableInWord {
public static void main(String[] args) {
try {
// path ของไฟล์
String fileName = "C:\\poi\\CreateTableInWord.docx";
// สร้างเอกสารเปล่าๆ
XWPFDocument document = new XWPFDocument();
// บันทึกเอกสารไว้ในระบบตาม path ที่ระบุ
FileOutputStream out = new FileOutputStream(fileName);
// สร้างตาราง
XWPFTable table = document.createTable();
// สร้างแถวแรกของตาราง
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");
// สร้างแถวที่สองของตาราง
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");
// สร้างแถวที่สามของตาราง
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("Word document table created.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
ไฟล์ที่ถูกสร้าง
ผลลัพธ์ที่ได้


0 comments:
Post a Comment