1.สร้างโปรเจคเพื่อจะทำการพัฒนาเว็บไซต์ขึ้นมา
2.นำ library นี้ไปใส่ไว้ในโฟลเดอร์ของโปรเจค [/code]
3.จากนั้นสร้างไฟล์ Excel ชื่อว่า filename
4.สร้างไฟล์ index.php ขึ้นมา
5.นำตัวอย่างโคดนี้ไปใส่ใน ไฟล์ index.php
โค้ด: เลือกทั้งหมด
<?php
set_time_limit(0);
header('Content-Type: text/html; charset=utf-8');
$mysqli = new mysqli('localhost','username','password','db_name'); //เชื่อมฐานข้อมูล
if ($mysqli->connect_errno) {
die( "Failed to connect to MySQL : (" . $mysqli->connect_errno . ") " . $mysqli->connect_error);
}
$mysqli->set_charset("utf8");
$inputFileName="filename.xlsx"; //สร้างตัวแปร ที่เก็บค่าตำแหน่งของไฟล์ Excel ที่จะนำมาแปลงข้อมูล
require_once 'PHPExcel/Classes/PHPExcel.php';
include 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($inputFileName);
$objWorksheet = $objPHPExcel->setActiveSheetIndex(0);
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$headingsArray = $objWorksheet->rangeToArray('A1:'.$highestColumn.'1',null, true, true, true);
$headingsArray = $headingsArray[1];
$r = -1;
$namedDataArray = array();
for ($row = 2; $row <= $highestRow; ++$row) {
$dataRow = $objWorksheet->rangeToArray('A'.$row.':'.$highestColumn.$row,null, true, true, true);
if ((isset($dataRow[$row]['A'])) && ($dataRow[$row]['A'] > '')) {
++$r;
foreach($headingsArray as $columnKey => $columnHeading) {
$namedDataArray[$r][$columnHeading] = $dataRow[$row][$columnKey];
}
}
}
foreach ($namedDataArray as $resx) {
//Insert
$query = " INSERT INTO tbl_name (field1,field2,field3,field4,field5,field6) VALUES
(
'".$resx['field1']."',
'".$resx['field2']."',
'".$resx['field3']."',
'".$resx['field4']."',
'".$resx['field5']."',
'".$resx['field6']."'
)";
$res_i = $mysqli->query($query);
//
}
$mysqli->close();
?>
ตัวอย่างข้อมูล จาก Excel
ตัวอย่างที่ได้หลังจากการใช้งาน
บทความที่เกี่ยวข้อง
การสร้าง Extension ใน phpbb
การสร้าง controller สำหรับ phpbb
Event listenner - เขียน Extension บน phpBB 3.1