How to read a uploaded file ($_FILE) with Spout

1.8k Views Asked by At

I am trying to make a page where the user can upload a correctly formatted Excel file (described in the manual) and let the file be inserted into the database.

I think I am able to insert the file into the database once Spout can read it but that part doesn't work. Can someone help me.

Edit: If it is of concern, the server where this program is on is shared.

Code:

// (1) FILE CHECK
// * HTML file type restriction can still miss at times
if (!isset($_FILES['upexcel']['tmp_name']) || !in_array($_FILES['upexcel']['type'], [
  'text/x-comma-separated-values',
  'text/comma-separated-values',
  'text/x-csv',
  'text/csv',
  'text/plain',
  'application/octet-stream',
  'application/vnd.ms-excel',
  'application/x-csv',
  'application/csv',
  'application/excel',
  'application/vnd.msexcel',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
])) {
  die("Invalid file type");
}

require_once "../database.php";
require_once '/src/Spout/Autoloader/autoload.php';


use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;

$reader = ReaderEntityFactory::createReaderFromFile($_FILES['upexcel']['tmp_name']);

$reader->open($_FILES['upexcel']['tmp_name']);
foreach ($reader->getSheetIterator() as $sheet) {
    foreach ($sheet->getRowIterator() as $row) {
        // do stuff with the row
        $cells = $row->getCells();
        echo "</br> Hello" .$cells;
    }
}

$reader->close();
2

There are 2 best solutions below

0
On

I'm using Spout and I had the same error, I did this and it work if you handle that the file is a .xlsx type.

Code:

$file = $_FILES['upexcel'];
$tmpName = $file ['tmp_name'];    
$reader = ReaderEntityFactory::createXLSXReader();
$reader ->open(tmpName);

This code its a example, you only need to change this:

$reader = ReaderEntityFactory::createReaderFromFile($_FILES['upexcel']['tmp_name']);

for this:

$reader = ReaderEntityFactory::createXLSXReader();
0
On

In Laravel:

$filepath = request()->file('excel_file')->getPathname();
$reader = ReaderEntityFactory::createXLSXReader();
$reader->open($filepath);