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 ต่างๆ เป็นต้น
Exness คือใคร และวิธีการเปิดบัญชี Exness (05/08/2024 15:45)
...อ่านต่อวิธีสร้างรายได้บน Pantip.com แค่เขียนกระทู้ก็ได้เงิน (27/11/2024 23:32)
...อ่านต่อออนเซ็น ม่อนแจ่ม ที่พักหน้าหนาว เชียงใหม่ (12/11/2024 12:00)
...อ่านต่อวิธีแสดงราคาบน Fibonacci MT4 และ MT5 (18/09/2024 17:00)
...อ่านต่อมาทำความรู้จัก ชูการ์ไกลเดอร์และโครงสร้างของชูการ์ไกลเดอร์กัน (08/08/2024 09:00)
...อ่านต่อ