หน้าเว็บ

Wednesday, September 23, 2015

ตัวอย่างประยุกต์การอ่านไฟล์ Excel และเขียนลง MySQL โดยใช้ PHPExcel

ตัวอย่างประยุกต์การอ่านไฟล์ Excel และเขียนลง MySQL โดยใช้ PHPExcel

โดยชื่อหัว Colum ของไฟล์ Excel จะเป็นดังนี้



Code

<?php
set_time_limit(0); 
require_once("connect.inc.php");

//File สำหรับ Import
$inputFileName="Leads.xlsx";

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

/** PHPExcel_IOFactory - Reader */
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];
        }
    }
}

$c=0;
foreach ($namedDataArray as $resx) {
 $c++; 
 echo "(".$c.") ".$resx['lead_no']." : ".$resx['firstname']."
";
 //Insert
  $query = " INSERT INTO vtiger_leaddetails (leadid,lead_no,email,firstname,lastname,company,mobile,phone,is_subscription) VALUES
      (
       '".$c."',
       '".$resx['lead_no']."',
       '".$resx['email']."',
       '".addslashes($resx['firstname'])."',
       '".addslashes($resx['lastname'])."',
       '".addslashes($resx['company'])."',
       '".addslashes($resx['mobile'])."',
       '".addslashes($resx['phone'])."',
       '".$resx['is_subscription']."'
      )";
  //echo $query."
";
  $res_i = $mysqli->query($query);
 //
}
$mysqli->close();
?>

สามารถดาวน์โหลด Class PHPExcel ได้จาก https://phpexcel.codeplex.com/

No comments:

Post a Comment