phpoffice/phpspreadsheet is a popular PHP library used for working with Excel files, including creating new files, reading data from existing files, and editing various data within Excel files.
Steps for Importing Data
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);
?>
With this, you can import data from an Excel file for further use, whether it is importing into a database or performing various validations, etc.
Onsen Mon Jam, winter accommodations in Chiang Mai (12/11/2024 12:00)
...Read moreLet's get to know sugar gliders and their structure (08/08/2024 09:00)
...Read moreHow to plant and care for Jamacaru (Cereus jamacaru) (24/04/2025 11:43)
...Read more