การสร้างไฟล์ Excel ด้วย NetBeans


หน้าแรก Netbeans การสร้างไฟล์ Excel ด้วย NetBeans
บางครั้งเราอาจมีความต้องการสร้างไฟล์ Excel แทนการสร้างรายงาน เนื่องจากเราสามารถทำการแก้ไขข้อมูลได้ง่ายในภายหลัง ในตัวอย่างนี้ผู้เขียนจะแสดงวิธีการสร้างไฟล์ Excel ด้วย NetBeans โดยทำงานบน Desktop Application ซึ่งหากต้องการใช้งานบนเว็บก็สามารถนำไปประยุกต์ใช้งานได้เช่นกัน

ก่อนอื่นขอให้ผู้อ่านดาวโหลดโปรแกรม POI ได้จาก ที่นี่

เมื่อดาวโหลดมาแล้ว ขอให้แตกไฟล์ไปที่เครื่องของเราเช่น C:POI หรือไดเร็กทอรี่อื่นๆก็ได้ จากนั้นให้เปิดโปรแกรม NetBeans แล้วสร้างโปรเจคใหม่แบบ Desktop Application แล้วนำ Button มาวางในฟอร์ม ที่หน้าต่าง Projects ใหคลิกขวาที่ Libraries แล้วเลือก Add JAR/Folder แล้วให้ browse ไปที่ตำแน่างที่เราได้แตกไฟล์ไว้ จากนั้นให้เลือกไฟล์ชื่อ poi-3.0.2-FINAL-20080204.jar (ชื่ออาจเปลี่ยนไปตามเวอร์ชั่นที่ดาวโหลด) แล้วคลิก OK

จากนั้นให้กลับไปที่หน้า Design แล้วสร้าง event ของ button แล้วแก้ไขโค้ดเป็นดังนี้

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            short rownum;
// create a new file
            FileOutputStream out = new FileOutputStream("workbook.xls");
// create a new workbook
            HSSFWorkbook wb = new HSSFWorkbook();
// create a new sheet
            HSSFSheet s = wb.createSheet();
// declare a row object reference
            HSSFRow r = null;
// declare a cell object reference
            HSSFCell c = null;
// create 3 cell styles
            HSSFCellStyle cs = wb.createCellStyle();
            HSSFCellStyle cs2 = wb.createCellStyle();
            HSSFCellStyle cs3 = wb.createCellStyle();
            HSSFDataFormat df = wb.createDataFormat();
// create 2 fonts objects
            HSSFFont f = wb.createFont();
            HSSFFont f2 = wb.createFont();
//set font 1 to 12 point type
            f.setFontHeightInPoints((short) 12);
//make it blue
            f.setColor((short) 0xc);
// make it bold
//arial is the default font
            f.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//set font 2 to 10 point type
            f2.setFontHeightInPoints((short) 10);
//make it red
            f2.setColor((short) HSSFFont.COLOR_RED);
//make it bold
            f2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            f2.setStrikeout(true);
//set cell stlye
            cs.setFont(f);
//set the cell format
            cs.setDataFormat(df.getFormat("#,##0.0"));
//set a thin border
            cs2.setBorderBottom(cs2.BORDER_THIN);
//fill w fg fill color
            cs2.setFillPattern((short) HSSFCellStyle.SOLID_FOREGROUND);
//set the cell format to text see HSSFDataFormat for a full list
            cs2.setDataFormat(HSSFDataFormat.getBuiltinFormat("text"));
// set the font
            cs2.setFont(f2);
// set the sheet name in Unicode
            wb.setSheetName(0, "u0422u0435u0441u0442u043Eu0432u0430u044F " + 
	"u0421u0442u0440u0430u043Du0438u0447u043Au0430", 
	HSSFWorkbook.ENCODING_UTF_16);
// in case of compressed Unicode
// wb.setSheetName(0, "HSSF Test", HSSFWorkbook.ENCODING_COMPRESSED_UNICODE );
// create a sheet with 30 rows (0-29)
            for (rownum = (short) 0; rownum < 30; rownum++) {
                // create a row
                r = s.createRow(rownum);
                // on every other row
                if ((rownum % 2) == 0) {
                    // set this cell to the first cell style we defined
                    r.setHeight((short) 0x249);
                }
                // make this column a bit wider
                // create 10 cells (0-9) (the += 2 becomes apparent later
                for (short cellnum = (short) 0; cellnum < 10; cellnum += 2) {
                    // create a numeric cell
                    c = r.createCell(cellnum);
                    // do some goofy math to demonstrate decimals
                    c.setCellValue(rownum * 10000 + cellnum + 
		        (((double) rownum / 1000) + ((double) cellnum / 10000)));
                    String cellValue;
                    // create a string cell (see why += 2 in the
                    c = r.createCell((short) (cellnum + 1));
                    // on every other row
                    if ((rownum % 2) == 0) {
                        // set this cell to the first cell style we defined
                        c.setCellStyle(cs);
                        // set the cell's string value to "Test"
                        c.setEncoding(HSSFCell.ENCODING_COMPRESSED_UNICODE);
                        c.setCellValue("Test");
                    } else {
                        c.setCellStyle(cs2);
                        // set the cell's string value to "u0422u0435u0441u0442"
                        c.setEncoding(HSSFCell.ENCODING_UTF_16);
                        c.setCellValue("u0422u0435u0441u0442");
                    }
                    // make this column a bit wider
                    s.setColumnWidth((short) (cellnum + 1), 
  			(short) ((50 * 8) / ((double) 1 / 20)));
                }
            }
//draw a thick black border on the row at the bottom using BLANKS
// advance 2 rows
            rownum++;
            rownum++;
            r = s.createRow(rownum);
// define the third style to be the default
// except with a thick black border at the bottom
            cs3.setBorderBottom(cs3.BORDER_THICK);
//create 50 cells
            for (short cellnum = (short) 0; cellnum < 50; cellnum++) {
                //create a blank type cell (no value)
                c = r.createCell(cellnum);
                // set it to the thick black border style
                c.setCellStyle(cs3);
            }
//end draw thick black border
// demonstrate adding/naming and deleting a sheet
// create a sheet, set its title then delete it
            s = wb.createSheet();
            wb.setSheetName(1, "DeletedSheet");
            wb.removeSheetAt(1);
//end deleted sheet
// write the workbook to the output stream
// close our file (don't blow out our file handles
            wb.write(out);
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(TestpoiView.class.getName()).log(Level.SEVERE, null, ex);
        }

    }                 

จากนั้นให้ทดลองรันโปรแกรมดู เมื่อคลิกที่ button เราจะพบว่าในโฟลเดอร์ของโปรเจคของเรามีไฟล์ใหม่ชื่อ workbook.xls ซึ่งคือไฟล์ Excel นั่นเอง ขอให้ผู้อ่านได้ลองเปิดดูแล้วเปรียบเทียบกับโค้ดข้างต้น เพื่อดูว่าแต่ละคำสั่งจะให้ผลเช่นไร เนื่องจากโค้ดนั้นมี comment ช่วยอธิบายแล้ว สุดท้ายนี้หวังว่าผู้อ่านคงจะนำความรู้ที่ได้จากบทความนี้ ไปใช้ให้เกิดประโยชน์ได้ไม่มากก็น้อย



ขึ้นไปด้านบน