จากโคดตัวอย่างเราจะสร้างไฟล์ .xlsx ดังนั้น ผู้เขียนจึงใช้ Package XSSF แต่หากใครจะสร้างไฟล์ .xls เฉยๆให้เรียกใช้ Package HSSF นะครับ
ตัวอย่างโคด
package com.java.poi.excel;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFComment;
import org.apache.poi.xssf.usermodel.XSSFCreationHelper;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CommentExcel {
public static void main(String[] args) {
try {
// สร้าง object ของ excel
XSSFWorkbook wb = new XSSFWorkbook();
// สร้าง sheet
XSSFSheet spreadsheet = wb.createSheet("Comment Excel");
// สร้างแถวแรก การนับแถวเริ่มจาก 0,1,2....
XSSFRow row = spreadsheet.createRow(3);
XSSFCreationHelper createHelper = wb.getCreationHelper();
XSSFCell cell = row.createCell(3);
cell.setCellValue("Test comment");
XSSFDrawing drawing = spreadsheet.createDrawingPatriarch();
XSSFClientAnchor anchor = createHelper.createClientAnchor();
// สร้าง comments
XSSFComment comment = drawing.createCellComment(anchor);
XSSFRichTextString str1 = createHelper.createRichTextString("Apache POI cell comments");
comment.setString(str1);
comment.setAuthor("Nop");;
comment.setColumn(2);
comment.setRow(2);
cell.setCellComment(comment);
// path ของไฟล์
FileOutputStream out = new FileOutputStream("C:\\poi\\CommentExcel.xlsx");
wb.write(out);
wb.close();
out.close();
System.out.println("Excel created successfully");
} catch (Exception e) {
e.printStackTrace();
}
}
}
ไฟล์ที่ถูกสร้าง
ผลลัพธ์ที่ได้


0 comments:
Post a Comment