How to read a uploaded xlsx file ($_FILE) with Spout in PHP?
Spout is a PHP library to read and write spreadsheet files (CSV, XLSX and ODS), in a fast and scalable way.
1. Code:
<?php
use Box\Spout\Reader\Common\Creator\ReaderFactory;
use Box\Spout\Common\Type;
require_once 'spout/src/Spout/Reader/Common/Creator/ReaderFactory.php';
require_once 'spout/src/Spout/Autoloader/autoload.php';
?>
<p>Choose File:</p>
<form action = "" method = "POST" enctype = "multipart/form-data">
<input type = "file" name = "filename" />
<input type = "submit"/>
</form>
<?php
$fileUploadData = $_FILES['filename'];
if (!empty($_FILES['filename']['name'])) {
$pathinfo = pathinfo($_FILES["filename"]["name"]);
if ($pathinfo['extension'] == 'xlsx' && $_FILES['filename']['size'] > 0 ) {
#Read excel file by using ReadFactory object.
$reader=ReaderFactory::createFromType(Type::XLSX);
$reader->open($fileUploadData['tmp_name']);
$count = 1;
$rows = array();
foreach ($reader->getSheetIterator() as $sheet) {
foreach ($sheet->getRowIterator() as $row) {
$rowAsArray = $row->toArray();
if ($count > 0) {
$fileUploadData['importData'][] = $rowAsArray;
}
$count++;
}
echo "successfully uploaded!";
}
$reader->close();
} else {
echo "PLEASE SELECT A VALID EXCEL FILE";
}
} else {
echo "UPLOAD AN EXCEL FILE";
}
?>
<p><?php echo($_FILES['filename']['name']) ?></p>
<table >
<?php foreach($fileUploadData['importData'] as $rows){?>
<tr>
<?php foreach($rows as $value){
?>
<td><?php echo($value); ?></td>
<?php } ?>
</tr>
<?php } ?>
</table>
<style>
table, td, th {
border: 1px solid;
}
table {
width: 100%;
border-collapse: collapse;
}
</style>
2. Example:
Input: example_upload_using_spout.xlsx
ID Name Description 1 Spout Spout is a PHP library to read and write spreadsheet files (CSV, XLSX and ODS) 2 ReaderFactory This creates an instance of the appropriate reader, given the type of the file to be read
Output
ID Name Description 1 Spout Spout is a PHP library to read and write spreadsheet files (CSV, XLSX and ODS) 2 ReaderFactory This creates an instance of the appropriate reader, given the type of the file to be read