phpoffice/phpspreadsheet เป็นไลบรารี PHP ที่นิยมใช้สำหรับการทำงานกับไฟล์ Excel ทั้งการสร้างไฟล์ใหม่ การอ่านข้อมูลจากไฟล์ที่มีอยู่ และการแก้ไขข้อมูลต่างๆ ภายในไฟล์ Excel
ขั้นตอนการ Import ข้อมูล
composer require phpoffice/phpspreadsheet
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Import Excel File Data with PHP</title>
</head>
<body>
<form action='importData.php' method='post' enctype='multipart/form-data'>
<table>
<tr>
<td>
<input type='file' class='form-control' name='file' id='fileInput' />
</td>
<td>
<input type='submit' class='btn btn-primary mb-3' name='importSubmit' value='Click to import data'>
</td>
</tr>
</table>
</form>
</body>
</html>
<?php
require_once 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
if(isset($_POST['importSubmit'])){
// Allowed type
$excelMimes = array('text/xls', 'text/xlsx', 'application/excel', 'application/vnd.msexcel', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
// บล็อกโค้ดนี้ตรวจสอบว่ามีการ Submit ฟอร์มที่มีปุ่มชื่อ importSubmit หรือไม่
if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'], $excelMimes)){
// is file is exist
if(is_uploaded_file($_FILES['file']['tmp_name'])){
$reader = new Xlsx();
$spreadsheet = $reader->load($_FILES['file']['tmp_name']);
$worksheet = $spreadsheet->getActiveSheet();
$worksheet_arr = $worksheet->toArray();
// Remove header row
unset($worksheet_arr[0]);
foreach($worksheet_arr as $row){
$first_name = $row[0];
$last_name = $row[1];
$email = $row[2];
$phone = $row[3];
$status = $row[4];
echo $first_name.'<br>';
echo $last_name.'<br>';
echo $email.'<br>';
echo $phone.'<br>';
echo $status.'<br>';
}
}
}
}
// Redirect to the listing page
header("Location: index_import.php".$qstring);
?>
เพียงเท่านี้ก็สามารถนำเข้าข้อมูลจากไฟล์ excel มาอ่านได้แล้วและสามารถนำมาใช้ในการทำงานต่อไปได้ ไม่ว่าจะนำเข้า Database หรือ Validate ต่างๆ เป็นต้น
รีวิว forex โบรกเกอร์ Exness ดีไหม ความน่าเชื่อถือ ข้อดีและข้อเสีย (10/11/2024 15:30)
...อ่านต่อวิธีแก้ Google Business Mail ไม่สามารถรับข้อความหรืออีเมล์ได้ (04/08/2024 05:00)
...อ่านต่อรีวิว petkit pura max ห้องน้ำแมวอัตโนมัติ (12/11/2024 11:22)
...อ่านต่อวิธีการใช้งาน plugin comment facebook บน website (07/08/2024 11:15)
...อ่านต่อเริ่มต้นเขียน EA บน MT4 ด้วยภาษา MQL4 ฉบับมือใหม่ (30/03/2025 07:30)
...อ่านต่อ