จากโคดตัวอย่างเราจะสร้างไฟล์ .xlsx ดังนั้น ผู้เขียนจึงใช้ Package XSSF แต่หากใครจะสร้างไฟล์ .xls เฉยๆให้เรียกใช้ Package HSSF นะครับ
ตัวอย่างโคด
package com.java.poi.excel;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
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 FillColorExcel {
public static void main(String[] args) {
try {
// สร้าง object ของ excel
XSSFWorkbook wb = new XSSFWorkbook();
// สร้าง sheet
XSSFSheet spreadsheet = wb.createSheet("Fill Color Excel");
// สร้างแถวแรก การนับแถวเริ่มจาก 0,1,2....
XSSFRow row = spreadsheet.createRow(2);
// ใส่สีพื้นหลัง
XSSFCellStyle style = wb.createCellStyle();
style.setFillBackgroundColor(IndexedColors.GREEN.index);
style.setFillPattern(XSSFCellStyle.BIG_SPOTS);
XSSFCell cell = row.createCell((short) 1);
cell.setCellValue(new XSSFRichTextString("Background color"));
cell.setCellStyle(style);
// ใส่สีพื้นหน้า หมายเหตุ : ไม่ใช่สีตัวอักษรนะครับ
style = wb.createCellStyle();
style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
cell = row.createCell((short) 2);
cell.setCellValue(new XSSFRichTextString("Foreground color"));
cell.setCellStyle(style);
// path ของไฟล์
FileOutputStream out = new FileOutputStream("C:\\poi\\FillColorExcel.xlsx");
wb.write(out);
wb.close();
out.close();
System.out.println("Excel created successfully");
} catch (Exception e) {
e.printStackTrace();
}
}
}
ไฟล์ที่ถูกสร้าง
ผลลัพธ์ที่ได้


0 comments:
Post a Comment