Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone
 

Registered : 109,027

HOME > บทความจากสมาชิก > สร้าง Excel (xls,xlsx) ไฟล์ด้วย PHPExcel และการส่งออก Export จากฐานข้อมูล MySQL Database



 
Clound SSD Virtual Server

สร้าง Excel (xls,xlsx) ไฟล์ด้วย PHPExcel และการส่งออก Export จากฐานข้อมูล MySQL Database

สร้าง Excel ไฟล์ด้วย PHPExcel และการส่งออกจาก MySQL เห็นมีปัญหากันบ่อย ๆ กับการสร้างเอกสาร Excel ซึ่งในบทความมีเฉพาะตัวอย่างการใช้ COM (Microsoft Office Excel) ที่อยู่บน Windows Server แต่พอนำไปใช้บน Linux Server กลับใช้งานไม่ได้ และยังมีปัญหากับ Office 2007 บทความนี้เลยแนะนำการใช้ Library ที่ชื่อว่า PHPExcel ใช้สำหรับการสร้างเอกสาร Excel ไฟล์ ซึ่งดีที่สุดในขณะนี้ สามารถรองรับการทำงานบน Excel 2007 และยังสามารถส่งออกเป็น Format รูปแบบอื่น ได้ เช่น PDF ซึ่งก็สามารถทำได้ไม่ยากเช่นเดียวกัน (รองรับนามสกุล .xls , .xlsx , .pdf)

Screenshot

PHPExcel MySQL

สำหรับ PHP กับ Excel ผ่าน COM ของ Windows อ่านได้ที่นี่


ตารางของ MySQL สำหรับใช้ในบทความ
CREATE TABLE `customer` (
  `CustomerID` varchar(4) NOT NULL,
  `Name` varchar(50) NOT NULL,
  `Email` varchar(50) NOT NULL,
  `CountryCode` varchar(2) NOT NULL,
  `Budget` double NOT NULL,
  `Used` double NOT NULL,
  PRIMARY KEY  (`CustomerID`)
) ENGINE=MyISAM;



INSERT INTO `customer` VALUES ('C001', 'Win Weerachai', '[email protected]', 'TH', 1000000, 600000);
INSERT INTO `customer` VALUES ('C002', 'John  Smith', '[email protected]', 'EN', 2000000, 800000);
INSERT INTO `customer` VALUES ('C003', 'Jame Born', '[email protected]', 'US', 3000000, 600000);
INSERT INTO `customer` VALUES ('C004', 'Chalee Angel', '[email protected]', 'US', 4000000, 100000);


Download Library PHPExcel


หลังจากดาวน์โหลดไฟล์ได้แล้วให้แตกไฟล์ใว้ใน Path ของ Server (ในตัวอย่างผมเก็บไว้ที่ C:\AppServ\www\PHPExcel\)

PHPExcel MySQL

ตามตัวอย่าง ดังรูป


ทดสอบรันการสร้าง Excel
http://localhost/PHPExcel/Tests/01simple.php


กรณี Error
08:32:13 Create new PHPExcel object 08:32:13 Set properties 08:32:13 Add some data 08:32:13 Rename sheet 08:32:13 Write to Excel2007 format
Fatal error: Class 'ZipArchive' not found in C:\AppServ\www\PHPExcel\Classes\PHPExcel\Writer\Excel2007.php on line 225


กรณี Error นี้โปรแกรมบอกว่าไม่สามารถอ้างถึง Class ที่ชื่อว่า 'ZipArchive' ซึ่งเราจะต้องทำการเปิด extension ของ php_zip.dll ก่อน


Download php_zip.dll


หลังจากดาวนืโหลด php_zip.dll ได้แล้วให้นำไปไว้ใน Path ของ extension ซึ่งตัวนี้ผมใช้ Appserv Version 2.5.9 จะอยู่ที่ C:\AppServ\php5\ext

เปิด extension โดยไปที่ php.ini

PHPExcel MySQL

ดูรูปประกอบ

Start -> Run -> php.ini
extension = php_zip.dll


หลังจากแก้ไขเรียบร้อยแล้วให้ทำการ Restart Apache ด้วยครับ








ทดสอบรันโปรแกรมใหม่อีกครั้ง ถ้าผ่านจะแสดงข้อความ

08:36:13 Create new PHPExcel object 08:36:13 Set properties 08:36:13 Add some data 08:36:13 Rename sheet 08:36:13 Write to Excel2007 format 08:36:13 Peak memory usage: 4.75 MB 08:36:13 Done writing file.


โดยไฟล์ Excel จะถุกจัดเก็บไว้ที่ PHPExcel\Tests\


PHPExcel MySQL

เปิดไฟล์ 01sample.xlsx ที่ถูกสร้าง หากต้องการสร้างเป็น Format อื่น ๆ ก็สามารถรันดู Demo ตามตัวอย่างในรูปจะเห็นว่ามี Demo อยู่มากมาย


PHPExcel MySQL

เปิดไฟล์ Excel ที่ถูกสร้าง





ทดสอบการส่งออกจาก MySQL Database

ExportMySql2Excel.php
<?php
/**
 * PHPExcel
 *
 * Copyright (C) 2006 - 2011 PHPExcel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category   PHPExcel
 * @package    PHPExcel
 * @copyright  Copyright (c) 2006 - 2011 PHPExcel (http://www.codeplex.com/PHPExcel)
 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt	LGPL
 * @version    1.7.6, 2011-02-27
 */

/** Error reporting */
error_reporting(E_ALL);

date_default_timezone_set('Europe/London');

/** PHPExcel */
require_once '../Classes/PHPExcel.php';


// Create new PHPExcel object
echo date('H:i:s') . " Create new PHPExcel object\n";
$objPHPExcel = new PHPExcel();

// Set properties
echo date('H:i:s') . " Set properties\n";
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
							 ->setLastModifiedBy("Maarten Balliauw")
							 ->setTitle("Office 2007 XLSX Test Document")
							 ->setSubject("Office 2007 XLSX Test Document")
							 ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
							 ->setKeywords("office 2007 openxml php")
							 ->setCategory("Test result file");


// Add some data
echo date('H:i:s') . " Add some data\n";
$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'CustomerID')
            ->setCellValue('B1', 'Name')
            ->setCellValue('C1', 'Email')
			->setCellValue('D1', 'CountryCode')
			->setCellValue('E1', 'Budget')
            ->setCellValue('F1', 'Used');

// Write data from MySQL result
$objConnect = mysql_connect("localhost","root","root") or die("Error Connect to Database");
$objDB = mysql_select_db("mydatabase");
$strSQL = "SELECT * FROM customer";
$objQuery = mysql_query($strSQL);
$i = 2;
while($objResult = mysql_fetch_array($objQuery))
{
	$objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $objResult["CustomerID"]);
	$objPHPExcel->getActiveSheet()->setCellValue('B' . $i, $objResult["Name"]);
	$objPHPExcel->getActiveSheet()->setCellValue('C' . $i, $objResult["Email"]);
	$objPHPExcel->getActiveSheet()->setCellValue('D' . $i, $objResult["CountryCode"]);
	$objPHPExcel->getActiveSheet()->setCellValue('E' . $i, $objResult["Budget"]);
	$objPHPExcel->getActiveSheet()->setCellValue('F' . $i, $objResult["Used"]);
	$i++;
}
mysql_close($objConnect);

// Rename sheet
echo date('H:i:s') . " Rename sheet\n";
$objPHPExcel->getActiveSheet()->setTitle('My Customer');


// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);


// Save Excel 2007 file
echo date('H:i:s') . " Write to Excel2007 format\n";
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$strFileName = "myData.xlsx";
$objWriter->save($strFileName);


// Echo memory peak usage
echo date('H:i:s') . " Peak memory usage: " . (memory_get_peak_usage(true) / 1024 / 1024) . " MB\r\n";

// Echo done
echo date('H:i:s') . " Done writing file.\r\n";
?>


จัดเก็บไฟล์ไว้ตามโครงสร้างซึ่งจต้องอยู่ที่ PHPExcel\Tests\ExportMySql2Excel.php








Screenshot

PHPExcel MySQL

Download!!


บทความอื่น ๆ ที่เกี่ยวข้อง
Go to : PHPExcel กับ Reader การอ่านไฟล์ Excel (.xls,.xlsx) และการนำเข้าฐานข้อมูล MySQL
Go to : PHP Excel (Excel.Application) : การใช้งาน PHP กับ Microsoft Excel
Go to : PHP CSV : การใช้งาน PHP กับ CSV ไฟล์


   
Share
Bookmark.   

  By : TC Admin
  Article : บทความเป็นการเขียนโดยสมาชิก หากมีปัญหาเรื่องลิขสิทธิ์ กรุณาแจ้งให้ทาง webmaster ทราบด้วยครับ
  Score Rating :
  Create Date : 2012-04-26
  Download : No files
Sponsored Links
ThaiCreate.Com Forum


Comunity Forum Free Web Script
Jobs Freelance Free Uploads
Free Web Hosting Free Tools

สอน PHP ผ่าน Youtube ฟรี
สอน Android การเขียนโปรแกรม Android
สอน Windows Phone การเขียนโปรแกรม Windows Phone 7 และ 8
สอน iOS การเขียนโปรแกรม iPhone, iPad
สอน Java การเขียนโปรแกรม ภาษา Java
สอน Java GUI การเขียนโปรแกรม ภาษา Java GUI
สอน JSP การเขียนโปรแกรม ภาษา Java
สอน jQuery การเขียนโปรแกรม ภาษา jQuery
สอน .Net การเขียนโปรแกรม ภาษา .Net
Free Tutorial
สอน Google Maps Api
สอน Windows Service
สอน Entity Framework
สอน Android
สอน Java เขียน Java
Java GUI Swing
สอน JSP (Web App)
iOS (iPhone,iPad)
Windows Phone
Windows Azure
Windows Store
Laravel Framework
Yii PHP Framework
สอน jQuery
สอน jQuery กับ Ajax
สอน PHP OOP (Vdo)
Ajax Tutorials
SQL Tutorials
สอน SQL (Part 2)
JavaScript Tutorial
Javascript Tips
VBScript Tutorial
VBScript Validation
Microsoft Access
MySQL Tutorials
-- Stored Procedure
MariaDB Database
SQL Server Tutorial
SQL Server 2005
SQL Server 2008
SQL Server 2012
-- Stored Procedure
Oracle Database
-- Stored Procedure
SVN (Subversion)
แนวทางการทำ SEO
ปรับแต่งเว็บให้โหลดเร็ว


Hit Link
   







Load balance : Server 02
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่