เนื้อหานี้จะเป็นเริ่มต้นการใช้งาน PhpSpreadsheet สำหรับการออกรายงานหรือสร้าง
ไฟล์ excel โดย PhpSpreadsheet เป็น PHP Library ที่พัฒนาใหม่มาใช้แทน PHPExcel ซึ่งปัจจุบัน
ไม่ได้มีการพัฒนาต่อแล้ว เนื้อหา PHPExcel ในเว็บไซต์ของเราก็ยังสามารถใช้งานได้ แต่แนะนำ
ให้เปลี่ยนมาใช้ตัวใหม่แทน
ความต้องการของโปรแกรม
สิ่งที่จะเป็นจะต้องมีเมื่อมีจะนำ PhpSpreadsheet ไปใช้งาน มีดังนี้้
- เป็น PHP เวอร์ชั่น 5.6 ขึ้นไป (เฉพาะเวอร์ชั่น 1.8.2 ลงมา) มากกว่า 1.8.2 ต้องใช้ PHP 7.1 ขึ้นไป
- เปิดใช้งาน php_zip extension
- เปิดใช้งาน php_xml extension
- เปิดใช้งาน php_gd2 extension
สามารถดูแนวทางการเปิดใช้งาน extension กรณีพัฒนาที่เครื่องด้วยโปรแกรมจำลอง server เช่น xampp ได้ที่บทความ
ตามลิ้งค์ http://niik.in/633 โดยดูตอนท้ายของบทความ
การติดตั้ง PhpSpreadsheet
เราจะใช้ composer เพื่อทำการติดตั้ง PhpSpreadsheet มาใช้งานในโปรเจ็คของเรา ด้วยคำสั่ง ด้านล่างผ่าน command line
1 2 | composer require phpoffice/phpspreadsheet // ใช้คำสั่งนี้จะได้เวอร์ชั่นล่าสุด จะต้องใช้ PHP 7.1 ขึ้นไป composer require phpoffice/phpspreadsheet:1.8.2 // ใช้คำสั่งนี้จะได้เวอร์ชั่นที่รองรับPHP 5.6 ขึ้นไป |
ทดสอบการทำงานเบื้องต้น
ให้เราสร้างไฟล์ชื่อ test.php แล้วกำหนดโค้ดดังนี้
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php // include composer autoload require 'vendor/autoload.php' ; // import the PhpSpreadsheet Class use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet ->getActiveSheet(); $sheet ->setCellValue( 'A1' , 'Hello World !' ); // กำหนดค่าใน cell A1 $sheet ->setCellValue( 'B1' , 'ทดสอบข้อความภาษาไทย !' ); // กำหนดค่าใน cell B1 $writer = new Xlsx( $spreadsheet ); $output_file = "hello_world.xlsx" ; // กำหนดชื่อไฟล์ excel ที่ต้องการ $writer ->save( $output_file ); // สร้าง excel if ( file_exists ( $output_file )){ // ตรวจสอบว่ามีไฟล์ หรือมีการสร้างไฟล์ แล้วหรือไม่ echo '<a href="' . $output_file . '" target="_blank">Download</a>' ; } |
รันไฟล์ test.php โดยเมื่อรันไฟล์ผ่านบราวเซอร์แล้ว หากไม่เกิดข้อผิดพลาดใดๆ ตัว PhpSpreadsheet จะทำการ
สร้างไฟล์ชื่อ hello_world.xlsx ไว้ที่ path เดียวกับไฟล์ test.php ดังรูป

ผลลัพธ์เมื่อรันผ่านบราเซอร์

ไฟล์ hello_world.xlsx
