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.
How to Fix Issues with Receiving Emails in Google Business Mail (04/08/2024 05:00)
...Read moreTravel to Osaka, Japan 2025 (7 Days) EP.1 My Beloved Osaka (07/03/2025 11:00)
...Read moreWhat is HTML and How Does it Relate to SEO? (16/06/2024 14:00)
...Read moreExness Forex Broker Review: Is It Reliable? Pros and Cons (27/11/2024 23:32)
...Read moreTesla Model 3 or Model Y, which one should I choose? (22/03/2025 15:00)
...Read more